Move Images with Javascript

Asked

Viewed 2,421 times

0

I would like an example of how I could move an HTML image using Javascript. For example the Image is in a position, when touching a button it moves.Thank you!

  • Canvas is an excellent option for this. This example basic well shows the displacement of a figure.

1 answer

4

Since I don’t know if you just want a button to move to only one side, :

<html>
<head>
<title>Demo of changing position of an Image in JavaScript</title>
<script language='JavaScript' type='text/JavaScript'>
<!--
function move_img(str) {
var step=50; // change this to different step value
switch(str){
case "down":
var x=document.getElementById('i1').offsetTop;
x= x + step;
document.getElementById('i1').style.top= x + "px";
break;

case "up":
var x=document.getElementById('i1').offsetTop;
x= x -step;
document.getElementById('i1').style.top= x + "px";
break;

case "left":
var y=document.getElementById('i1').offsetLeft;
y= y - step;
document.getElementById('i1').style.left= y + "px";
break;

case "right":
var y=document.getElementById('i1').offsetLeft;
y= y + step;
document.getElementById('i1').style.left= y + "px";
break;
}
}
//-->
</script>
</head>
<body>
<img src=images/help.jpg id='i1' style="position:absolute; left: 500; top: 100;">
<br><br><br><br>
<input type=button onClick=move_img('up') value='Up'>
<br>
<input type=button onClick=move_img('left') value='Left'>
<input type=button onClick=move_img('right') value='right'>
<br>
<input type=button onClick=move_img('down') value='down'>
<br><br> Return to <a href=image-move.php>image move tutorial</a>
</body>
</html>

Example of this working code : http://www.plus2net.com/javascript_tutorial/image-move-demo.php

NOTE: You can also change the variable if you want the image to move more or even less step where 50 is how much she will move.

  • Following your example, I put it in jsfiddle so it is easier to see the separate codes https://jsfiddle.net/fb00t8Lq/1/ :)

  • @Tonato Thanks friend, I will also put in the answer if you do not mind :)

  • Make yourself at home ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.