Search code examples
javascriptjquerycssmouse-cursor

Hide mouse cursor if idle inside a div after some seconds


How do I let mouse hiding if inactive and inside a specific div ? I have the "html5gallery-box-0" div on my website, and I need the mouse to hide if the user let it idle over/inside the div after a couple of seconds. Here's the jsfiddle I'm working on.

And here's the js I'm using to hide the mouse when it's inactive.

$(function () {
    var timer;
    var fadeInBuffer = false;
    $(document).mousemove(function () {
        if (!fadeInBuffer) {
            if (timer) {
                console.log("clearTimer");
                clearTimeout(timer);
                timer = 0;
            }

                console.log("fadeIn");
            $('html').css({
                cursor: ''
            });
        } else {
            fadeInBuffer = false;
        }


        timer = setTimeout(function () {
            console.log("fadeout");
            $('html').css({
                cursor: 'none'
            });
            fadeInBuffer = true;
        }, 500)
    });
});

Solution

  • This will work

     $(function() {
        var timer;
        var fadeInBuffer = false;
        $(document).mousemove(function() {
            if (!fadeInBuffer && timer) {
                console.log("clearTimer");
                clearTimeout(timer);
                timer = 0;
    
                console.log("fadeIn");
                $('html').css({
                    cursor: ''
                });
            } else {
                $('.html5gallery-box-0').css({
                    cursor: 'default'
                });
                fadeInBuffer = false;
            }
    
    
            timer = setTimeout(function() {
                console.log("fadeout");
                $('.html5gallery-box-0').css({
                    cursor: 'none'
                });
    
                fadeInBuffer = true;
            }, 2000)
        });
        $('.html5gallery-box-0').css({
            cursor: 'default'
        });
    });
    

    and here is the fiddle (if you want to change the idle time just do it, it's on 2 seconds now).

    http://jsfiddle.net/eugensunic/1Lsqpm3y/4/