Animated css sprites with mootools

Adding a little extra to plain menus using javascript to animate changes insted of instant changes for mouse hovers. Most menu effects are easy to animate, I will show you how to animate a gradient for the background which would nomaly snap from top to bottom, to tween between these positions.

HTML

<ul id="menu">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>

CSS

#menu li {
    display: inline;
    list-style-type: none;
    margin: 0px;
}
#menu li a {
    padding: 5px 10px;
    background: transparent url("bg.gif") repeat-x left top;
    color: #ffffff;
}
#menu li a:hover {
    background: transparent url("bg.gif") repeat-x left bottom;
}

background image




Javascript

$("menu").getElements("a").each( function(item, index) {
    var fx = new Fx.Morph(item, {duration: '600', link: 'cancel'});
    item.addEvents({
        "mouseenter" : function() {
            fx.start({"background-position" : "0px -170px", "color" : "#ff0000"});
        },
        "mouseleave" : function() {
            fx.start({"background-position" : "0px 0px", "color" : "#ffffff"});
        }
    });
});


Run down of the javascript

First we want to select all anchor elements that we want to apply the effect to.

$("menu").getElements("a")

we could of also used:

$$("#menu a")

You can read more about mootools selectors here


Next we want to loop through all element and add events to trigger the animation using the each method.

.each( function(item, index) {} );

Before adding any events its important to setup an effect object for each element and not for each event as this will cause a flickering effect when triggering the events multiple times. It is also important to include the option link: 'cancel' to cancel the event when another one is triggered.

var fx = new Fx.Morph(item, {duration: '600', link: 'cancel'});


For this example I used Fx.Morph so I can have more than one effect, for my events I wanted to change the colour font and background.

fx.start( {

      "background-position" : "0px 0px",
      "color" : "#ffffff"

} );


Demo

Leave a comment

Bookmark with

choen 5th Mar, 2009
nice tutor bro... btw can i have download this tutor or send me to: one.choen@yahoo.com thanks before.
choen 5th Mar, 2009
i interest whit "back top of page" in your blog... u have tutor to... hehhe sorry ..thanks
Post a comment

About

Welcome to my online portfolio and development site where i can share my developments and projects.

Ive been developing for 7 years working mainly with online applications and websites.

Download my CV or

Favorites

RSS Feed Subscribe
RSS or Atom

Copyright 2010 kd3sign.co.uk     Best viewed in Mozilla Firefox
hosted by Media Temple powered by CodeIgniter