Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - detect if the mouse is still?

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!

like image 556
ModernDesigner Avatar asked Dec 30 '12 20:12

ModernDesigner


People also ask

How do I know if my mouse is hovering?

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.

What is Mouseout 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.

What is the difference between Mouseout and Mouseleave?

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).

How can write hover function in jQuery?

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);


2 Answers

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).

like image 113
Felix Kling Avatar answered Sep 23 '22 01:09

Felix Kling


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);
})();
like image 20
Niet the Dark Absol Avatar answered Sep 25 '22 01:09

Niet the Dark Absol