4/23/2016

Move an Image from Left to Right in Javascript for Onclick

How to move/slide an image from left to right by 10px. Create an HTML page insert an image and button in the page when a click to a button image should shift to the right with 10px value. This is a simple javascript code that allows shifting the image by some particular pixel in this case we are shifting an image by 10px. Now come to the logic for solving this problem in javascript. Follow the given steps.

Step 1: First create a simple form in an HTML and add an image with some height and width in my case I choose the 400px height and 600px width, Here px means pixel.

Step 2: Now add a button, this is the most important part of our program cause without a button we can not perform a specific part of our program.

Step 3: This is a part where we are adding a functionality of task that we have to perform, So add a javascript code to shift an image by 10px.

Step 4: Define a function in button we added in step 2 so when we click on the image the image will shift to the right direction with some or specific pixels in our case 10px.

Step 5: Till now we added all the functionality of a program, now time to perform a task we did so click on the image if it's moving or shifting to the right direction as we choose than our program is working fine without any doubt. Now you can modify the problem for other direction, for example, Left, Up, and Down.

Task: You have to change the direction of a program for all 4 directions, Right, left, Up, and Down, You can use 4 buttons for each direction.

Code start here, save the program as a suggested name for remembering easy.

Moving Image Across Screen from Left to Right


changedirenction.html

<!DOCTYPE html>
   <head>
      <title>JavaScript Animation</title>
      <script type="text/javascript">
        <!--
            var imgObj = null;
           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';
            }
            window.onload =init;
         //-->
      </script>
   </head>
   <body>
      <form>
         <img id="myImage" src="Desert.jpg" height="400" width="600" />
         <p>Click button below to move the image to right</p>
         <input type="button" value="Click Me" onclick="moveRight();" />
      </form>
   </body>
</html>

Output:-

javascript move image across screen by 10px before

After Clicking 30 Time Image Reach Next Point Approx 300 Px

How to move images using JavaScript/jquery from left to right

No comments:

Post a Comment