0

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 ?

oneandonlycore
  • 480
  • 6
  • 23

2 Answers2

3

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/

Paul Rad
  • 4,820
  • 1
  • 22
  • 23
0

Your position is the actual position - the div position:

$('.content').mousemove(function(e){
        var pos=$(this).position();
        $('#xCoord').val(e.pageX-pos.left);
        $('#yCoord').val(e.pageY-pos.top);
    });

http://jsfiddle.net/B7zZ8/3/

ojovirtual
  • 3,332
  • 16
  • 21