birdus
birdus

Reputation: 7504

Trouble getting mouse position with jQuery

I have an onmouseover event attached to an anchor. I'm trying to get the mouse position within that event handler, but the coordinates are coming back as undefined. Here's what I'm trying:

<a onmouseover="SetTopLeft(this);"...

<script type="text/javascript">
    function SetTopLeft(obj)
    {
        alert("width/height = " + obj.pageX + "/" + obj.pageY);
    }
</script>

I've also tried:

alert("width/height = " + $(obj).pageX + "/" + $(obj).pageY);

...with the same results.

What am I doing wrong?

Upvotes: 0

Views: 79

Answers (2)

Lyn Headley
Lyn Headley

Reputation: 11598

alert("width/height = " + $(obj).offset().left + "/" + 
($(obj).offset().top - $(window).scrollTop());

Upvotes: 1

Hidde
Hidde

Reputation: 11961

Search a little on Google first...

Docs: http://docs.jquery.com/Tutorials:Mouse_Position

Code:

$(document).ready(function(){
   $(document).mousemove(function(e){
      $('#status').html(e.pageX +', '+ e.pageY);
   }); 
})

If you need the position of the object, you can use:

$(selector).position()

Upvotes: 0

Related Questions