TheYaXxE
TheYaXxE

Reputation: 4294

Div reappears after fadeout on mousemove

I'm having a div which I want to fade in, when the mouse is moving. If the mouse is idle for about 3 seconds I then want the div to fade out.

It works, but there's a tiny problem. If you move the mouse again a couple of times right after the div has appeared and then let the mouse idle for 3 seconds, the div is sometimes fading in again, right after it has faded out. I have no idea why this is happening and why it only happens sometimes.

The script I'm using is from another thread on this post: Jquery: how to make something fade out...

I've tried to reset time in the end of setTimeout-function with no luck.

Here's my code:

HTML:

<div class="object">
</div>

CSS:

.object {
    display: none;
    width: 100px;
    height: 100px;
    background: red;
}

JavaScript/jQuery:

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

    $('.object').fadeIn(300);

    timer = setTimeout(function() {
        $('.object').fadeOut(300);
        time = 0;
    }, 3000);

});

Fiddle

Anyone who please can help me? :)

Upvotes: 0

Views: 497

Answers (2)

webnoob
webnoob

Reputation: 15934

I think you need to be looking at: Hover Intent.

It handles problems with hovering over an element, then moving out, then back in etc. I've used it with much success on things like this. It also allows you to keep hover triggered when going over child elements so nesting becomes easier.

Upvotes: 0

Aidan
Aidan

Reputation: 1750

if you only want the fade to happen once you need a variable to keep track of whether or not its the first time. I've added a boolean to the code:

var timer;
var first = true;
$(document).mousemove(function() {
    if (timer) {
        clearTimeout(timer);
        timer = 0;
    }
    if (first) {
        $('.object').fadeIn(300);

            timer = setTimeout(function() {
                $('.object').fadeOut(300);
                timer = 0;
                first = false;
            }, 3000);
    }         
});

jsfiddle

Upvotes: 1

Related Questions