Web animation with CSS and jQuery (Part 2)

Last time two pure CSS approaches were used to fade an article when it was hovered. Unfortunately this approach works well in Firefox and Webkit based browsers (Chrome and Safari) but is dead on arrival in even the newest version of Internet Explorer. Despite the fact that its market share is decreasing it is never a good idea to lock out 35%+ of your user base. Let's use jQuery to create a truly cross platform approach.

The Framework

Because we will be relying on Javascript to do the heavy lifting there is not much to the CSS. Two declarations are all that is needed to set a default state.

    #jquery_carousel article {
       opacity: 0.5;
       font-size: 75%;
    }

The real work occurs using Javascript's hooks to tie our animation to the hover event. The code below only works with jQuery but it would be trivial to implement a general solution instead. You would just have to rely on setTimeout [http://www.w3schools.com/js/js_timing.asp] method to do the heavy lifting. Instead the simple code block below works

    $('#jquery_carousel article').hover(
      function scaleArticle() {
        $(this).animate({
          'opacity': 1,
          'font-size': '100%'
        }, 2000);
      },
      function shrinkArticle() {
        $(this).animate({
          'opacity': 0.50,
          'font-size': '75%'
        }, 2000);
      });

Embedding this at the end of the page so that it fires as soon as everything on the page has loaded we now have a functioning cross browser scaling approach. The hover method takes two arguments in this instance. The first is executed immediately. The second will run as soon as our main method (scaleArticle) is done to shrink it back down. Both inner functions use jQuery's core animate method.

Three approaches, one result

As this final version shows each solution is not without its own gotchas. Relying solely on a CSS approach means that people in different browsers will see different effects. Using Javascript means either hand coding methods that are cross browser compatible or leveraging a framework like jQuery. Either way you increase the size of the page considerably compared to a few simple lines of CSS.

So which is better? The answer is that it depends on your situation. If you are developing in a controlled environment (such as for mobile devices based around Webkit) use the features available. If you want something that has the same experience across all modern browsers I'd suggest sticking with Javascript for the time being. Both give you considerably more flexibility than falling back on Flash or some other proprietary solution.