Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery mousemove offset relative to listening element on bubbled event

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/

like image 869
arcyqwerty Avatar asked Apr 20 '15 18:04

arcyqwerty


1 Answers

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.

like image 175
arcyqwerty Avatar answered Oct 03 '22 09:10

arcyqwerty