Search code examples
javascriptjquerymouse-position

jQuery determine mouse position within a div


this is maybe a duplicate question but I havent seen a working solution for me

My question is how can I get the mouse position within a div?

I dont want the document as origin but the inner div (the pink content div) so when I move the coursor to the (0|0) coordinate of the pink div I want also the (0|0) coordinates as my origin coordinates

I've setup a jsfiddle here

$('.content').mousemove(function(e){
    $('#xCoord').val(e.pageX);
    $('#yCoord').val(e.pageY);
});

this wont really work for me ... and I also tried it with

var parentOffset = $(this).parent().offset();

but I just get an offset of 8px returned and the jQuery mousemove offset is undefined

can anyone help me ?


Solution

  • e.pageX returns the current mouse position referring to the window.

    Try this:

    var mouseX = e.pageX - $(this).offset().left;
    var mouseY = e.pageY - $(this).offset().top;
    

    Updated fiddle: http://jsfiddle.net/B7zZ8/2/