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!
Answer: Use the CSS :hover Pseudo-class 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.
jQuery mouseout() MethodThe mouseout event occurs when the mouse pointer leaves the selected element. The mouseout() method triggers the mouseout event, or attaches a function to run when a mouseout event occurs.
This means that mouseleave is fired when the pointer has exited the element and all of its descendants, whereas mouseout is fired when the pointer leaves the element or leaves one of the element's descendants (even if the pointer is still within the element).
The hover() is an inbuilt method in jQuery which is used to specify two functions to start when mouse pointer move over the selected element. Syntax: $(selector). hover(Function_in, Function_out);
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);
});
DEMO
This can be very easily done without jQuery as well (only binding the event handler here is jQuery-specific).
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);
})();
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