I try to get mouse position relative to an element using mousemove. It works fine, but when the mouse hover a child element, the coordinates are relative to this child. I want the mouse position relative to the parent div, not the child.
See this JSFiddle for example.
var object = document.getElementsByClassName('object'),
scene = document.getElementById('scene');
function initMove() {
for(var i=0; i<object.length; i++) {
object[i].addEventListener("mousemove", function(event) {
//event.stopPropagation();
return false;
}, false);
}
scene.addEventListener("mousemove", function (event) {
//event.stopPropagation();
//event.currentTarget;
moveX = event.offsetX;
moveY = event.offsetY;
console.log(moveX + ' + ' + moveY);
}, false);
}
function init() {
initMove();
document.onselectstart = function(){ return false; }
};
init();
Adding event.stopPropagation()
on child return no data.
And I'm not sure how event.currentTarget
works.
I can't use mouseenter or every other mouse only controls, because I want this to be touch friendly (by replacing mousemove by touchmove).
Any ideas?
In your above code for mousemove
, try using the following for moveX
and moveY
:
moveX = event.clientX - scene.offsetLeft;
moveY = event.clientY - scene.offsetTop;
Also, you forgot #
in $('scene')
.
Here is an updated JSFiddle.
Use mousemove
and the cursor coordinates to get the global mouse position. Then substract the offset of your child element from this.
var scene = $('#scene');
scene.mousemove(function(e){
var offsetX = e.pageX - scene.offset().left;
var offsetY = e.pageY - scene.offset().top;
});
Your whole script could look like the following tested example which lets you move to object in the scene.
jQuery(document).ready(function(){
var scene = $('#scene');
var object = $('.object');
scene.mousemove(function(e){
// get offset of object relative to scene
var offsetX = e.pageX - scene.offset().left;
var offsetY = e.pageY - scene.offset().top;
// grab object in it's center (optional)
offsetX -= object.width() / 2;
offsetY -= object.height() / 2;
// don't left to object out of the scene
var maxX = scene.width() - object.width();
var maxY = scene.height() - object.height();
if(0 > offsetX) offsetX = 0;
else if(offsetX > maxX) offsetX = maxX ;
if(0 > offsetY) offsetY = 0;
else if(offsetY > maxY) offsetY = maxY;
// delete decimals
offsetX = Math.floor(offsetX);
offsetY = Math.floor(offsetY);
// debug information
object.html('X: ' + offsetX + '<br>Y: ' + offsetY);
// move object
object.css('left', offsetX).css('top', offsetY);
});
});
Is this what you wanted to do? Here is your fiddle: http://jsfiddle.net/Bp3wH/9/ (If you like see this version with only optical improvements http://jsfiddle.net/Bp3wH/11/)
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