student student - 4 years ago 200
HTML Question

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?

Answer Source

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 (imgObj.style.left.replace("px","") >= 200) {
    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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download