Search code examples
javascripthtmlcssanimationcss-animations

Resetting position based on style.right


I was trying to reset animation when the image reaches right-most edge of the screen.

Everything works perfectly fine without this line:

if (imgObj.style.right == 0) {
    Reset();
}

Is it not the right way?

<!--
var imgObj = null;
var animate;

function init() {
  imgObj = document.getElementById('myImage');
  imgObj.style.position = 'relative';
  imgObj.style.left = '0px';
}

function moveRight() {
  imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
  animate = setTimeout(moveRight, 2000); // call moveRight in 20msec
  if (imgObj.style.right == 0) {
    Reset();
  }
}

function Reset() {
  clearTimeout(animate);
  imgObj.style.left = '0px';
}
window.onload = init;
//-->
<form>
  <img id="myImage" src="http://jsfiddle.net/img/logo.png" />
  <p>Click the buttons below to handle animation</p>
  <input type="button" value="Start" onclick="moveRight();" />
  <input type="button" value="Reset" onclick="reset();" />
</form>

How to get the animation working along with that above line?


Solution

  • You have some mistakes

    1. onclick="Reset();" not onclick="reset();"

    2. parseInt(imgObj.style.left.replace("px","")) not parseInt(imgObj.style.left)

    3. imgObj.style.right is always "" you have to set some thing like imgObj.style.left.replace("px","")>200

    var imgObj = null;
    var animate;
    
    function init() {
      imgObj = document.getElementById('myImage');
      imgObj.style.position = 'relative';
      imgObj.style.left = '0px';
    }
    
    function moveRight() {
     
      imgObj.style.left = parseInt(imgObj.style.left.replace("px","")) + 10 + 'px';
      
      animate = setTimeout(moveRight, 2000); // call moveRight in 20msec
     
      if (parseInt(imgObj.style.left.replace("px",""))+ imgObj.width>= window.innerWidth) {
        Reset();
      }
    }
    
    function Reset(){
    
     clearTimeout(animate);
     imgObj.style.left = '0px';
    }
    window.onload = init;
    <form>
      <img id="myImage" src="http://jsfiddle.net/img/logo.png" />
      <p>Click the buttons below to handle animation</p>
      <input type="button" value="Start" onclick="moveRight();" />
      <input type="button" value="Reset" onclick="Reset();return false;" />
    </form>