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
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
Share Improve this question asked Nov 3, 2012 at 4:46 mark cassadaymark cassaday 1531 gold badge1 silver badge4 bronze badges2 Answers
Reset to default 17The 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);
(function(){
var moved = false
window.onmousemove = function(e){
if(!moved){
moved = true;
// do what you want after mousemove, here
}
}
})()