2

I need to write a javascript code inside an HTML document that has the following behavior: When a button is clicked, an image starts moving (if it is not already moving), one pixel to the left per second. When a second button is clicked, the image stops moving and immediately gets repositioned to its original coordinates.

I get everything to work, except for the "Button" that says "START". Right now if I click the image the image moves left 1 pixel per second. However I need to carry that function over to the button called START.

Does anyone know how to do this? Thank you!!

My code is as follow:

<html><head>


<script>

var timerid = null;


function move()
{
document.getElementById('cat').style.right = 
    parseInt(document.getElementById('cat').style.right) + 1 + 'px';    
}

window.onload=function()
{   



document.getElementById('cat').onclick=function(){

    if(timerid == null){
        timerid = setInterval("move()", 10);
    }else{
        clearInterval(timerid);
        timerid = null;
    }
}   


var button2 = document.getElementById('button2');
button2.onclick= reloadPage;

    function reloadPage(){
        window.location.reload();
    }

}


</script>
</head>
<body>

<img id="cat" src="cat.jpg" style="position:absolute;right:5px"/>

<div>
<button id="button1" type="button" style="position:absolute;left:10px;top:190px"/>START</button>
<button id="button2" type="button" style="position:absolute;left:10px;top:220px"/>STOP & RESET</button>
</div>

</body>
</html>
2
  • Things would be much easier by using jQuery which provides this out of the box with .animate() Commented Mar 29, 2013 at 7:15
  • Thanks I know! I am not allowed to use Jquery for this:( Commented Mar 29, 2013 at 7:26

1 Answer 1

1

change cat to button1

document.getElementById('button1').onclick=function(){
                     //--^^^^^^^^----here
  if(timerid == null){
    timerid = setInterval("move()", 10);
  }else{
    clearInterval(timerid);
    timerid = null;
  }
}   
Sign up to request clarification or add additional context in comments.

2 Comments

HI Bipen, You seem to be a pretty good javascript coder. Can I ask you to take a look at another piece of code that I am struggling with. This one might be a little of a challenge. I have spend hours on this one and nothing yet. Please see link: stackoverflow.com/q/15696938/2147761 Your help is much appreciated and I thank yo in advance!!
@user2147761 ok updated you answer back there check the fiddle out in the answer.. :).. and yes if any of the post helps you, then so should not forget to accept it as answer....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.