Friday, January 20, 2017

javascript - How to know element position while it move





There is way to obtain x,y data of a moving element (while it move...), something like:



$(document).mousemove(function (e) {
var x = e.pageX,
y = e.pageY;

...
}


but referred to a specific element (i.e. $("#mydiv"))?


Answer



The pageX/pageY variables in the event object refers to the mouse position. If you want to get the position of the element you should do something like this:



$(document).on('mousemove', function(e) {
var element = $('#myDiv');

console.log( element.offset() );
// returns an object with x/y coordinates of the top-left corner of the element
});


Checkout the documentation for .offset() for more info.


No comments:

Post a Comment