I'm looking for a small piece of javascript that will check for mouse movement and in the event it does execute a function. I'm looking to do this without jquery and preferably compatible with most modern browsers. I have this small script which detects when the mouse isn't moving:
<script>
document.onmousemove = (function() {
var onmousestop = function() {
/* do stuff */
}, thread;
return function() {
clearTimeout(thread);
thread = setTimeout(onmousestop, 500);
};
})();
</script>
I'm hoping things can be edited into firing the do stuff when the mouse is moved for the first time after loading the script? Any help? Thanks
JavaScript is implemented as part of a Web browser and is supported by all the major web browsers, including Internet Explorer, Firefox and Safari. Therefore, using this language, Web developers can track user's mouse movements simply by entering lines of code on a page.
To get the current mouse position we are going to trigger a mouse event. In this case we will use 'mousemove' to log the current X and Y coordinates of the mouse to the console.
The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.
You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery.
The problem with Amit's solution is that it removes any existing mousemove listeners. Also, it doesn't clean up when the mouse is first moved, and thus creates unnecessary overhead.
This is the clean way of doing it:
var myListener = function () {
document.removeEventListener('mousemove', myListener, false);
// do stuff
};
document.addEventListener('mousemove', myListener, false);
See it in action: http://jsfiddle.net/JQBmA/
If you need to support older IEs, you can use this:
var addListener, removeListener;
if (document.addEventListener) {
addListener = function (el, evt, f) { return el.addEventListener(evt, f, false); };
removeListener = function (el, evt, f) { return el.removeEventListener(evt, f, false); };
} else {
addListener = function (el, evt, f) { return el.attachEvent('on' + evt, f); };
removeListener = function (el, evt, f) { return el.detachEvent('on' + evt, f); };
}
var myListener = function () {
removeListener(document, 'mousemove', myListener);
// do stuff
};
addListener(document, 'mousemove', myListener);
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