Reputation: 480
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 ?
Upvotes: 0
Views: 102
Reputation: 3362
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);
});
Upvotes: 0
Reputation: 4882
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/
Upvotes: 3