Watch
Watch Repeating Animation Fix screencast (Alternative flash version)
QuickTime version is approximately 15Mb, flash version is streaming.
View the demo used in the screencast
The Problem
I was recently asked to look at Dan Cederholm‘s web site for a particular effect, but something I immediately noticed was the cool looking hover over/hover off effect on his images.
Wondering whether this was a CSS effect or done with jQuery, I did my usual repeat test: mouse over and out several times.
Unfortunately the effect goes a little wild. Admittedly this isn’t something the average user is going to do, but it is certainly possible that they’ll mouse over by accident, go out, then back in again to see what the text under behind the effect was. This would trigger a double effect, which I think still looks a little odd.
The fix is pretty easy once you know what to look out for.
Chainging to fadeTo
Dan’s original site code is:
$('.picture a').hover(function () {
$(this).find('strong').fadeIn('normal');
}, function () {
$(this).find('strong').fadeOut('normal');
});
There’s 3 things we need to do to stop this effect from happening:
- Add
stop()
before the fade effect to prevent previous effects from finishing - Change the fade effects to use
fadeTo(speed, opacity)
so they can animate from mid opacity - Change the CSS from
display:none
on thestrong
element toopacity: 0
$('.picture a').hover(function () {
$(this).find('strong').stop().fadeTo('normal', 1);
}, function () {
$(this).find('strong').stop().fadeTo('normal', 0);
});
Now the effect handles mousing over several times, and doesn’t continuously trigger.
Try the demo by moving your mouse over and out of the image.
Arguably, since the site’s CSS is using rgba(0, 0, 0, 0.746094)
to handle the semi-opaque effect, you could get rid of the rgba
in favour of a solid black background, and change the fadeTo('normal', 1)
to fadeTo('normal', 0.746094)
. However, it should be noted, that use the opacity in the fade, rather than rgba
results in the text being slightly transparent too, which may or may not be the desired effect.
You should follow me on Twitter here I tweet about jQuery amongst the usual tweet-splurges!