Klaim
Klaim

Reputation: 69672

How to move an image to the mouse position in html/javascript?

I'm getting slowly back to javascript and I'm a bit lost on basics. I just want to move an image to follow the mouse position. Here is a simple code I've been tweaking for some time without any success :

<html>
<head>

</head>
<body>

<img id="avatar" src="Klaim.png" style="position:absolute;" />
</body>

<script lang="javascript">

function updateAvatarPosition( e )
{
    var avatar = document.getElementById("avatar");
    avatar.x = e.x;
    avatar.y = e.y;

    // alert( "e( " + e.x + ", " + e.y + " )" );    
    // alert( "avatar( " + avatar.x + ", " + avatar.y + " )" );
}

document.onmousemove = updateAvatarPosition;


</script>

</html>

It looks a lot like some tutorials to do this very thing. What I don't understand is that using the alerts (I don't know how to print in the browser's javascript console) I see that avatar.x and y are never changed. Is it related to the way I've declared the image?

Can someone point me what I'm doing wrong?

Upvotes: 1

Views: 14267

Answers (4)

Kev
Kev

Reputation: 187

<html>
<head>

</head>
<body>

<img id="avatar" src="Klaim.png" style="position:absolute;" />
</body>

<script lang="javascript">

function updateAvatarPosition( e )
{
    var avatar = document.getElementById("avatar");
    avatar.style.left = e.x + "px";
    avatar.style.top = e.y + "px";

    //alert( "e( " + e.x + ", " + e.y + " )" );    
    //alert( "avatar( " + avatar.x + ", " + avatar.y + " )" );
}

document.onmousemove = updateAvatarPosition;


</script>

</html>

Upvotes: 2

MooGoo
MooGoo

Reputation: 48230

avatar.style.top = e.clientY + 'px';
avatar.style.left = e.clientX + 'px';

Upvotes: 1

chrisfrancis27
chrisfrancis27

Reputation: 4536

There is no x and y property for avatar - you should use 'top' and 'left' instead. Also, move the var avatar = document.getElementById("avatar"); declaration outside of the function, as you only need to do this once.

Upvotes: 2

Sascha Galley
Sascha Galley

Reputation: 16091

I think that you don't want to set x and y, but rather style.left and style.top!

avatar.style.left = e.x;
avatar.style.top = e.y;

Upvotes: 4

Related Questions