Truvia
Truvia

Reputation: 370

jQuery mouseenter and mouseleave fadeTo prevent delayed repeat

So, I've got a div which fades up on mouse enter and down on mouseleave which works fine.

$('.myDiv').mouseenter(function(){
$(this).fadeTo('slow', 1);
});

$('.myDiv').mouseleave(function(){
$(this).fadeTo('slow', 0.4);
});

See jsfiddle .

However, if you quickly move the mouse over and back and again several times, the div will "flash" as the animation keeps running. Is there a way to stop this from occurring?

I've tried callbacks but haven't got the desired effect.

Any suggestions?

Upvotes: 1

Views: 675

Answers (2)

Stefan Koenen
Stefan Koenen

Reputation: 2337

A better way is to use CSS. Javascript shouldn't be used for this kind of animation as it will make your website slow. See my example below.

.fade {
        background-color: red;
    width: 200px;
    height: 200px;  
   opacity: 0.4;
    filter: alpha(opacity=40); /* For IE8 and earlier */
   transition: opacity .25s ease-in-out;
   -moz-transition: opacity .25s ease-in-out;
   -webkit-transition: opacity .25s ease-in-out;
    cursor: pointer;
   }

   .fade:hover {
      opacity: 1;
      }
<div class='fade'></div>

Upvotes: 2

Khanh TO
Khanh TO

Reputation: 48982

Try:

$('.myDiv').mouseenter(function(){
    $(this).stop();
    $(this).fadeTo('slow', 1);

});
$('.myDiv').mouseleave(function(){
    $(this).stop();
    $(this).fadeTo('slow', 0.4);
});

https://jsfiddle.net/1Lrcubwp/

Upvotes: 2

Related Questions