Fidel Cashflow
Fidel Cashflow

Reputation: 21

Reset animation to original position using javascript

using the following script i was able to move my picture right when clicked:

<script>
var myTimer = null;

function move(){
    document.getElementById("fish").style.left = 
        parseInt(document.getElementById("fish").style.left)+1+'px';
}


window.onload=function(){

    document.getElementById("fish").onclick=function(){
        if(myTimer == null){
            myTimer = setInterval("move();", 10);
        }else{
            clearInterval(myTimer);
            myTimer = null;
        }
    }
}
</script>

I am having some trouble reseting the picture to original location without using jQuery.

If anyone can help that would be much appreciated.

Upvotes: 1

Views: 100

Answers (3)

Sebastian Souto
Sebastian Souto

Reputation: 1

This should work fine,



    
    var myTimer = null;
    var startX = 0;

    function move(){
        document.getElementById("fish").style.left = 
            parseInt(document.getElementById("fish").style.left)+1+'px';
    }


    window.onload=function(){

        document.getElementById("fish").onclick=function(){
            if(myTimer == null){
                startX = document.getElementById("fish").style.left;
                myTimer = setInterval("move();", 10);
            }else{
                clearInterval(myTimer);
                myTimer = null;
                document.getElementById("fish").style.left = startX + "px";
            }
        }
    }
    

Upvotes: 0

StackSlave
StackSlave

Reputation: 10627

Use external JavaScript. Some code to look at:

var pre = onload, E, doc, bod;// previous onload
onload = function(){
if(pre)pre();

doc = document; bod = doc.body;
E = function(id){
  return doc.getElementById(id);
}
var fish = E('fish'), timer;
fish.onclick = function(){
  if(!timer){
    timer = setInterval(function(){
      fish.style.left = parseInt(fish.style.left)+1+'px';
    }, 10);
  }
  else{
    clearInterval(timer); timer = false;
    fish.style.left = '0'; // change '0' to what your CSS `left:`value is
  }

}// end load

Upvotes: 0

Bo Borgerson
Bo Borgerson

Reputation: 1406

If you capture the original position ahead of time you can reset later to the captured value:

var originalPosition = document.getElementById("fish").style.left;

function resetPosition() {
    document.getElementById("fish").style.left = originalPosition;
}

Upvotes: 4

Related Questions