Search code examples
javascriptjquerycssmouse-cursor

Fade out mouse cursor when inactive (with jQuery)


I have an element with class fade-object that fades out when the mouse is inactive for a certain amount of time (5000 milliseconds in this case), and fades back in when the mouse is moved again.

This is the code I'm using:

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

            $('.fade-object').fadeIn();
            timer = setTimeout(function() {
                $('.fade-object').fadeOut()
            }, 5000)
        })

How do I make it so the mouse cursor fades in and out the same way, in sync with my fade-object div?


Solution

  • Set cursor: none in the CSS of the html and prevent the mousemove event that occurs directly after a fadeout from re-displaying the item.

    Demo

    $(function () {
        var timer;
        var fadeInBuffer = false;
        $(document).mousemove(function () {
            if (!fadeInBuffer) {
                if (timer) {
                    clearTimeout(timer);
                    timer = 0;
                }
                $('.fade-object').fadeIn();
                $('html').css({
                    cursor: ''
                });
            } else {
                fadeInBuffer = false;
            }
    
    
            timer = setTimeout(function () {
                $('.fade-object').fadeOut()
                $('html').css({
                    cursor: 'none'
                });
                fadeInBuffer = true;
            }, 5000)
        });
    });