Bennet G.
Bennet G.

Reputation: 585

jQuery mouseenter / mouseleave glitching

When I hover inside the box it fades out and in continuously. I don't know why or if that is only on my Browser (Siri), but you have to play with it a bit to realize my problem.

I'm trying to fade it out when I stay in the field, and fade it in again when I leave it.

Here is the fiddle

HTML:

<div class="ani-bounce-slow"></div>

CSS:

div {
    height: 200px; 
    width: 200px; 
    background-color: #3c3;
}

jQuery:

$('.ani-bounce-slow').mouseenter(function() {
    $('.ani-bounce-slow').fadeOut('slow');
});
$('.ani-bounce-slow').mouseleave(function() {
    $('.ani-bounce-slow').fadeIn('slow');
});

Upvotes: 1

Views: 495

Answers (2)

max
max

Reputation: 8687

When you hover over your box it fades out, so there is no box there anymore (therefore your function on mouseleave fires).

Better way is to use opacity in this case:

CSS:

div {
    height: 200px; 
    width: 200px; 
    background-color: #3c3;
    transition: opacity 1s;
}
.fade {
    opacity: 0;
}

JS:

$('.ani-bounce-slow').mouseenter(function () {
    $('.ani-bounce-slow').addClass('fade');
})
$('.ani-bounce-slow').mouseleave(function () {
    $('.ani-bounce-slow').removeClass('fade')
});

OR:

$('.ani-bounce-slow').hover(function () {
  $(this).toggleClass('fade');
});

JSFIDDLE

Upvotes: 5

Gregg Duncan
Gregg Duncan

Reputation: 2725

"fadeOut" fades the element then sets a class of display: none; which means it's no longer taking up space within the DOM. Because it's moved from under your mouse your mouseout event triggers causing it to fadeIn again.

if you animate the opacity. It will fadeOut but still take up space within the DOM so your mouse is still over the element. It won't fade in until you mouseout.

$('.ani-bounce-slow').hover(function(){
    $(this).animate({ opacity: 0 }, 800);
}, function(){
    $(this).animate({ opacity: 1 }, 800);
});

http://jsfiddle.net/9sftLjk8/7/

Upvotes: 0

Related Questions