Christopher Kornosky
Christopher Kornosky

Reputation: 73

Getting a box to fade out when mouse is still and fade back in when mouse moves

I have been having trouble getting this basic code to correctly function. I have looked up solutions but I suppose I lack required knowledge to implement them because I'm still unable to get the silly box to fade when the mouse is still. Any help on this would be appreciated, here is my condensed code:

<!DOCTYPE html>
    <html>
    <head>
        <style>
        #box {
            height: 100px;
            width: 100px;
            background-color: green;
        }
        </style>
        <script>
        var fadeout = null;
        $(document).mousemove(function() {
        $("#box").stop().fadeIn("slow");
        if (fadeout != null) {
            clearTimeout(fadeout);
        }
        fadeout = setTimeout(hide_playlist, 3000);
    });
        function hide_playlist() {
        $("#box").stop().fadeOut("slow");
    }</script>

    <title>Page Title</title>
    </head>

    <body>
    <div id="box"></div>
    <h1>Why wont you work.</h1>
    </body>
    </html>

Upvotes: 2

Views: 46

Answers (2)

tdurtschi
tdurtschi

Reputation: 151

First off, make sure you are referencing jquery in your file before your script.

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

Second, you only set the timeout upon the first page load, so when you clear it with clearTimeout, it never gets set again. I got it to work with this small tweak:

var fadeout = null;
    $(document).mousemove(function() {
        $("#box").stop().fadeIn("slow");
        if (fadeout != null) {
            clearTimeout(fadeout);
            fadeout = setTimeout(hide_playlist, 3000); //added this line!
        }
        fadeout = setTimeout(hide_playlist, 3000);
    });

    function hide_playlist() {
    $("#box").stop().fadeOut("slow");
    }

Upvotes: 1

Josh
Josh

Reputation: 1474

You should try using mouseenter and mouseleave with opacity transitions.

Here is my jsfiddle example: https://jsfiddle.net/z19q19yu/

$('#box').mouseenter(function(){
    $(this).css('opacity', '1');
})
$('#box').mouseleave(function(){
    $(this).css('opacity', '0.3');
})

Upvotes: 1

Related Questions