<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'>
On click of each button we will take the direction to a function move_img() inside JavaScript area. Based on the direction we will execute a switch() statement.
Out of four directions, this switch condition will match one direction and accordingly set the new position of the image after reading the image present position. Let us see the when Up button is clicked.
case "up":
var x=document.getElementById('i1').offsetTop;
x= x -step;
document.getElementById('i1').style.top= x + "px";
break;
In above code we first read the vertical coordinate value of the image and store it in variable x. As we are moving up so we will subtract step value from x . Now we can re-position the image by updating the new style.top value.
x=x+step;
Here is the complete code.
<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>
The above code moves the image in steps, we can further improve the script to give continues movement to the image. It is like dropping the image from a height. We will learn in part II of moving image.