Question

I'm trying to set up a script in a webpage that does the following: if the mouse is inactive for a certain amount of time (say, five seconds), perform an action (say, hiding an element); then, if the mouse of moved, perform an action (say, un-hiding the element).

What I want is some way to perform an action on user mouse inactivity (not necessarily keyboard inactivity).

Thanks for your help.

Was it helpful?

Solution

If you are using jQuery:

(function() {
    var timeout;
    var isHidden = false;
    $(document).mousemove(function() {
        if (timeout) {
            window.clearTimeout(timeout);
        }
        timeout = window.setTimeout(function() {
            if (!isHidden) {
                //hide the element here
                isHidden = true;
            }
        }, 5000);
        if (isHidden) {
            //show the element here
            isHidden = false;
        }
    });
})();

Non jQuery version:

(function() {
    var timeout;
    var isHidden = false;

    function hideOnIdle() {
        if (timeout) {
            window.clearTimeout(timeout);
        }
        timeout = window.setTimeout(function() {
            if (!isHidden) {
                //hide the element here
                isHidden = true;
            }
        }, 5000);
        if (isHidden) {
            //show the element here
            isHidden = false;
        }
    }

    if (document.addEventListener) {
        document.addEventListener("mousemove", hideOnIdle);
    } else {
        document.attachEvent("onmousemove", hideOnIdle);
    }
})();

jsfiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top