Reputation: 268
var mousemove = function(event) {
var xpos = event.x || event.clientX;
console.log(xpos);
}
window.addEventListener('mousemove', mousemove);
I have the following code which works beautifully on Chrome and Firefox but typically on IE doesn't. IE seems to be reporting the mouse position relative to the current element it's hovered over or the focal point is being switched somewhere and it's getting confused, rather than the window which the event is bound to.
The code is used on a off-canvas navigation system i am working to calculate if the mouse is less than 5% from the left of the screen (where the navigation is situated).
Any ideas on getting it to play nicely would be awesome.
Upvotes: 3
Views: 1669
Reputation: 877
There are a lot of ways to do it. One way is using jQuery.
$(window).mousemove(function(event){console.log(event.clientX);});
Upvotes: 0
Reputation: 2377
This function returns mouse position relative to the viewport or relative to the page.
var getMousePosition = function(e, relativeToViewport) {
var x = relativeToViewport ? e.clientX : e.pageX || e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
var y = relativeToViewport ? e.clientY : e.pageY || e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
return {
x: x,
y: y
};
};
Upvotes: 0
Reputation: 268
Thanks Tero for the resource and helping me get this fixed, please find the revised code below.
var mousemove = function(event) {
var xpos = event.screenX;
console.log(xpos);
}
window.addEventListener('mousemove', mousemove);
Upvotes: 1