Search

Play School: Broken Repeating Animations

Posted on 23rd July 2009 — jQuery makes it incredibly easy to add effects to your web sites, but there’s some effects you just don’t want: the hover repeatedly to make the effect go wild!

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:

  1. Add stop() before the fade effect to prevent previous effects from finishing
  2. Change the fade effects to use fadeTo(speed, opacity) so they can animate from mid opacity
  3. Change the CSS from display:none on the strong element to opacity: 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.