Detecting Mouse Movement with jQuery

Javascript / jQuery can help in capturing Mouse move, Scroll and Click events

Option 1 – Capturing Mouse move along with Click and Scroll


var timeout = null;

$(document).on('mousemove click scroll', function() {
    clearTimeout(timeout);

    timeout = setTimeout(function() {
        console.log('Mouse idle for 3 sec');
    }, 3000);
});

Option 2 – Capturing Mouse with Javascript


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

Addon – Fade some DIV tag when mouse is idle


var timer;
$(document).mousemove(function() {
    if (timer) {
        clearTimeout(timer);
        timer = 0;
    }

    $('#top:visible').fadeIn();
    timer = setTimeout(function() {
        $('#top').fadeOut()
    }, 3000)
})

Leave a Reply

Your email address will not be published.