Thursday, February 22nd, 2007

ClassAnim & HoverHijax: Keeping Presentation out of Your JavaScript

Category: JavaScript, Library, Toolkit, UI, Yahoo!

Jeremy Gillick wants to keep the peanut butter separate from his jam, and to aide this has written a couple of YUI extensions to help out:

When you’re animating a rollover or fading some colors do you stop and thing what you’re doing? You’re putting the colors, dimensions and effects into your JavaScript! The presentation layer that you’ve worked so hard to externalize is leaking into your JavaScript code. This is a slippery slope that we have to prevent now. The presentation layer should remain in the CSS, markup in the HTML and logic in the JavaScript. If you want to change the colors or sizes the elements are morphed into, you should be making those changes in CSS.

How it works

  1. ClassAnim starts by reading the styles from the base element.
  2. Then it quickly applies the new CSS class to it, reads the new styles and removes the class. This happens quicker than the user can notice.
  3. Now it compares the styles from both versions, extracts the differences that can be animated, and invokes the animation.

HoverHijax animates colors and does it on mouseover and mouseout. My original prototype would actually honor the :hover pseudo class, but good ‘ol Internet Explorer wasn’t allowing me to get to those styles through JavaScript. The current implementation adds a ‘hover’ class to all links when they are being moused over.

javascript

  1. YAHOO.util.Event.onAvailable("TestClassAnim", function() {
  2.   var anim = new YAHOO.mozmonkey.ClassAnim("TestClassAnim");
  3.   var start = 0;
  4.  
  5.   YAHOO.util.Event.addListener("TestClassAnim", "mouseover", function() {
  6.     anim.addClass("classAnimHover");
  7.   });
  8.   YAHOO.util.Event.addListener("TestClassAnim", "mouseout", function(){
  9.     anim.removeClass("classAnimHover");
  10.   });
  11.   YAHOO.util.Event.addListener("TestClassAnim", "click", function(){
  12.     if(start == 0){
  13.       start = 1; anim.addClass("classAnim2");
  14.     } else{
  15.       start = 0; anim.removeClass("classAnim2");
  16.     }
  17.   });
  18. });

Posted by Dion Almaer at 6:02 am
1 Comment

+++--
3.7 rating from 18 votes

1 Comment »

Comments feed TrackBack URI

Thats cool.

Comment by Toas — June 21, 2008

Leave a comment

You must be logged in to post a comment.