How to make an image move by clicking on a button with Javascript?

15,300

change cat to button1

document.getElementById('button1').onclick=function(){
                     //--^^^^^^^^----here
  if(timerid == null){
    timerid = setInterval("move()", 10);
  }else{
    clearInterval(timerid);
    timerid = null;
  }
}   
Share:
15,300
tidydee
Author by

tidydee

Updated on June 04, 2022

Comments

  • tidydee
    tidydee almost 2 years

    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>