jQuery - detect if the mouse is still?
16,275
Solution 1
You can listen to the mousemove
event, start a timeout whenever it occurs and cancel any existing timeout.
var timeout = null;
$(document).on('mousemove', function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
console.log('Mouse idle for 3 sec');
}, 3000);
});
This can be very easily done without jQuery as well (only binding the event handler here is jQuery-specific).
Solution 2
No need for a plugin, or even for jQuery at all:
(function() {
var idlefunction = function() {
// what to do when mouse is idle
}, idletimer,
idlestart = function() {idletimer = setTimeout(idlefunction,3000);},
idlebreak = function() {clearTimeout(idletimer); idlestart();};
if( window.addEventListener)
document.documentElement.addEventListener("mousemove",idlebreak,true);
else
document.documentElement.attachEvent("onmousemove",idlebreak,true);
})();
Author by
ModernDesigner
Updated on June 04, 2022Comments
-
ModernDesigner almost 2 years
I was wondering if there was a way to detect if the mouse is idle for like 3 seconds in jQuery. Is there a plugin that I am unaware of? Because I don't believe there to be a native jQuery method. Any help would be much appreciated!
-
ModernDesigner over 11 yearsThank you! This is just what I was looking for. :-D
-
jfriend00 over 11 yearsProbably want to set
timeout
back tonull
after the timer fires to avoid doing an invalidclearTimeout()
. -
Ry- over 11 years@jfriend00: Doesn't matter, really. whatwg.org/specs/web-apps/current-work/multipage/… Even the
null
check. -
ModernDesigner over 11 years@FelixKling OK, so what I did was used this in conjunction with the jScrollPane plugin so that if the user is idle for 3 seconds, the scrollbar fades out of visibility. How can I make it to where it re-appears when the user is not idle? (e.g. when he/she moves the mouse?) I tried making an entirely separate function but it is not working.
-
Felix Kling over 11 years@ModernDesigner: Just put in inside the event handler. The
mousemove
event is triggered (as the same says) whenever the mouse moves, i.e. it is not idle anymore. Just have a look how I remove the text in the demo. -
ModernDesigner over 11 years@FelixKling ahh, thanks! That's it. And I did take a look at your Possible Duplicate Proposition, and the plugin linked there seems very helpful as well. I'll take both of those into consideration. Thanks again!
-
jfriend00 over 11 years@minitech - if you want to send invalid handles to
clearTimeout()
go ahead. I don't program that way nor would I counsel others to do so. In my book, it's sloppy programming and it takes one extra line of code to follow a better general practice. -
Ry- over 11 years@jfriend00: I never said I did, but you were pointing it out like it mattered and it turns out that it doesn't, is all. I've always avoided doing that too.