I want to get mouse coords of a div, like this:
$("#box").mousemove(function(e){
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
document.getElementById("coords").innerHTML = x + ", " + y; });
But I also want to be able to tell if the cursor was moved to left or right; I know I just have to compare current mouse position with previous one, but I have no idea how to do it in this case.
Any help appreciated. Thank you
The jquery code to get the mouse position is the following
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
Obviously you must have a div called "status"
<div id="status">0, 0</div>
To check if the cursor is moving to the left or to the right you're right, you must store the previous position and then compare it with the new.
Here I wrote you the complete example:
http://jsfiddle.net/cB9Wq/
_ EDIT :
If you need to get the coords inside a div you need to know also the position of the div:
$(".div_container").mousemove(function(e){
var relativeXPosition = (e.pageX - this.offsetLeft); //offset -> method allows you to retrieve the current position of an element 'relative' to the document
var relativeYPosition = (e.pageY - this.offsetTop);
$("#header").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
}).mouseout(function(){
$("#header").html("<p>Move mouse on the below blue div container! :)</p>")
});
To check if the mouse goes to the left or to the right, I used this sintax:
xPrev<e.pageX ? $('#lr').html("right") : $('#lr').html("left");
xPrev=e.pageX;
NB: This is the equivalent to:
if(xPrev<e.pageX) {
$('#lr').html("right");
}
else {
$('#lr').html("left");
}
xPrev=e.pageX;
Here you have the working example: http://jsfiddle.net/cB9Wq/2/
You can use the following solution:
var plotSliderLastPostion = 0; //Placed outside the scope of function (fxp like private member)
slider.addEventListener(EVENT.MOUSE_MOVE, function(e){
var relativePlotBoxPositionX = e.clientX - rect.left;
//CHECK THAT CURSOR IS MOVING RIGHT OR LEFT
if(relativePlotBoxPositionX > plotSliderLastPostion) {
console.log("right");
plotSliderLastPostion = relativePlotBoxPositionX;
}
else {
console.log("left");
plotSliderLastPostion = relativePlotBoxPositionX;
}
}, true);
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