i want to make an animation using setInterval. The image has to change its position from left to right.
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>animacja</title>
<style type="text/css">
#obrazek
{
position: relative;
left: 1px;
}
</style>
<script type="text/javascript" src="animacja.js"></script>
</head>
<body>
<img src="smile.jpg" id="obrazek" alt="Usmiech" width="100" height="100" />
</body>
</html>
JavaScript:
window.onload = inicjuj;
function inicjuj()
{
setInterval(function(){animacja();},1000);
}
function animacja()
{
var obj = document.getElementById("obrazek");
var wartosc = parseInt(obj.style.left, 10);
obj.style.left = (wartosc + 10) + "px";
}
Unfortunalety js doesn’t work and i don’t know why. I’ve checked and the animacja function runs however the image isn’t changing its position.
Your problem is that
obj.styleonly contains information about styles that are specified in thestyletag, not style specified in other style sheets, like your<style>tag. Thus,obj.style.leftis the empty string, andparseInt('')yieldsNaN.Instead, define your
leftstyle property in thestyleproperty of the<img>tag:Or, if it’s very important to keep the styles in separate (e.g. to adhere to some design standard), you can use the
window.getComputedStylefunction to figure out the object’s actualleftstyle value: