Moving an image

W

Willem-Jan

Hi all,

Im trying to move an image by javascript and i created the following code:


<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">

function move()
{
myimg.style.left += 10;
}

</SCRIPT>

</head>

<body>

<img id="myimg" src="dot.gif" height="10" width="10">
<BR>
<a href="#" onclick="move()">Move</a>

</body>
</html>


Can anyone tell me why the image wont move when i use the link and what
i can do to make the image move?

Thanx!
 
M

michael elias

Hi,

Only absolutely and relatively position elements can be positioned
using the left, top, right and bottom style attributes.

<img id="myimg" style="position:absolute; left:20px; top:20px"
src="dot.gif" height="10" width="10"/>

Be aware that positioning an element absolute, it will be relative to
the browser document or to a parent element that has it's position
attribute set to relative.
 
B

binnyva

Hi,

Try the below code...

<html>
<head>
<script language="JavaScript">
function moveImage() {
//Move the image to the new location
document.getElementById("myimg").style.left = 100;
}
</script>
<style type="text/css">
#myimg {
position:absolute;
}
</style>
</head>

<body>
<img id="myimg" src="dot.gif" />

<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>

<a href="javascript:moveImage();">Move</a>
</body>
</html>

There are two reasons why your code did not work

1) The position must be given as absolute - you can use
<img id="myimg" src="dot.gif" style="position:absolute;" />
to do it. Otherwise, the image is pretty much stuck where it is.
This change will give that element the ability to move to a new
position
given by absolute x,y co-ordinates.

2) You used
myimg.style.left ...
This is not W3C standard. This will work in most browsers
- but please use the W3C recommended
document.getElementById("myimg").style.left

Hope this helps.

Binny V A
http://www.geocities.com/binnyva/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top