1

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?

Truvia
  • 370
  • 1
  • 3
  • 14

2 Answers2

2

Try:

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

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

https://jsfiddle.net/1Lrcubwp/

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
2

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>
Stefan Koenen
  • 2,289
  • 2
  • 20
  • 32
  • Although using CSS is a preferred option for me generally and this is a good response, technically the scope of the question was javascript or jquery based so marked the other answer as correct if anyone is looking at this in the future. However, I'm probably going to use this version! – Truvia Jun 07 '15 at 09:49
  • Also, for anyone else looking for this, if you want to use CSS to change the opacity of a different element when hovering over the original div, combine this method with [this answer here](http://stackoverflow.com/questions/6910049/on-a-css-hover-event-can-i-change-another-divs-styling) – Truvia Jun 07 '15 at 10:07