Search code examples
javascriptfunctioncall

How to execute my javascript function in javascript


Here is my code that makes an image move to the right. I have searched how to call and execute functions but I don't understand they.

I know how to execute it in HTML but not in javascript. I want to execute it when I load the page all the time.

<input type="button" value="Start" onclick="moveRight();" />

I have seen this code but I can't get it to work with my code.

window["functionName"](arguments);

like what I'm supposed to write in the brackets for example.

<script>
        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) + 11 + 'px';
           animate = setTimeout(moveRight,22); // call moveRight in 20msec
        }

<body>

  <form>
     <img id="myImage" src="myimage.jpg" />
     <p>Click the buttons below to handle animation</p>
     <input type="button" value="Start" onclick="moveRight();" />
      <input type="button" value="Start" onclick="moveLeft();" />
     <input type="button" value="Stop" onclick="stop();" />
  </form>

Solution

  • A slight extension to @Emil's answer above so that the code will execute as soon as page is loaded.

    Using setInterval(), providing moveRight() as the function parameter and 200 as the delay will keep calling your function every 200 milliseconds. You can also use clearInterval() to cancel the timer.

    You may want to extend this further to prevent image from going off-screen (if this is a requirement).

    var img = document.getElementById("myImage"); 
    var imgLeft = 0;
    var imgTop = 0;
    img.style.position = "absolute";
    
    function render() {
      img.style.left = imgLeft + "px";
      img.style.top = imgTop + "px";
    }
    
    function moveRight() {
      console.log(img.style.left);
      imgLeft += 10;
      render();
    }
    var interval = setInterval(moveRight, 200);  
       
    <form>
      <img id="myImage" src="myimage.jpg" />      
    </form>