If I have jQuery listen for the mousemove
event on an "outer" element, the offsetX
and offsetY
values give an offset relative to an "inner" element when the mouse is within that inner element and the event bubbles to the handler.
How can I always get the offset relative to the element to which the handler is attached?
Example: http://jsfiddle.net/00mo3eeu/
HTML
<div class="outer">
<div class="inner"></div>
</div>
CSS
.outer {
background: red;
width: 300px;
height: 400px;
margin: 40px;
}
.inner {
background: blue;
width: 100px;
height: 150px;
margin: 70px;
display: inline-block;
}
JS
$('.outer').mousemove(function(e) {
console.log([e.offsetY, e.offsetX]);
});
Update: in case it's not clear, get the dot to follow the pointer even in the blue box http://jsfiddle.net/00mo3eeu/1/
This is my current solution and I welcome any suggestions to improve it.
function (e) {
var y = e.pageY - $(e.currentTarget).offset().top
var x = e.pageX - $(e.currentTarget).offset().left
...
}
Ideally this would be given as one of the properties on the event object, but I can't find one that matches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With