Reputation: 8457
I have this simple code set up so that when I mouseenter
an image, the image fades out and some text info fades in. My problem is that when I hover over the image very quickly back and forth, it records every mouseenter
and fades in and out continuously for the amount of times my mouse hovered over the image. Is there some way to stop this behavior?
$('article').mouseenter(function(e) {
$(this).children('img').fadeTo(500, 0.4);
$(this).children('.post-info').fadeIn(500);
}).mouseleave(function(e) {
$(this).children('img').fadeTo(500, 1);
$(this).children('.post-info').fadeOut(500);
});
Upvotes: 0
Views: 42
Reputation: 7305
.stop() is the solution
In simple terms, you just add .stop()
in front of every fade animation.
$('article').mouseenter(function(e) {
$(this).children('img').stop().fadeTo(500, 0.4);
$(this).children('.post-info').stop().fadeIn(500);
}).mouseleave(function(e) {
$(this).children('img').stop().fadeTo(500, 1);
$(this).children('.post-info').stop().fadeOut(500);
});
As a bonus. This is how I would've written that code:
$('article').on("mouseenter mouseleave", function( e ) {
// mouseenter variable returns true if mouseenter event is occurring
// and it returns false if event is anything but mouseenter.
var mouseenter = e.type === "mouseenter",
$this = $(this),
img = $this.children('img'),
postInfo = $this.children('.post-info');
// Both of these use ternary if statements that are equal to:
// if ( mouseenter ) { var imgFade = 0.4; } else { var imgFade = 1; }
// if ( mouseenter ) { var postInfoFade = 'fadeIn'; } else { var postInfoFade = 'fadeOut'; }
var imgFade = mouseenter ? 0.4 : 1,
postInfoFade = mouseenter ? 'fadeIn' : 'fadeOut';
img.stop().fadeTo( 500, imgFade );
postInfo.stop()[ postInfoFade ]( 500 );
});
Upvotes: 1