Fade One Image to Another Menu

Avatar of Chris Coyier
Chris Coyier on (Updated on )

Make a CSS sprite image, with the top half and the bottom half being the two images you want to animate between. The jQuery adds a <span> tag, and adds the bottom half of the sprite image as its background. As you hover on and off, the span animates between fully transparent and fully opaque, fading one image into another.

HTML:

<ul id="menu">
       <li id="home"><a href="#">home</a></li>
       <li id="about"><a href="#">about</a></li>
       <li id="services"><a href="#">services</a></li>
       <li id="contact"><a href="#">contact</a></li>
</ul>

CSS:

ul#menu li a{float:left;display:block;background:url("images/menu.png")  no-repeat;width:150px;text-indent:-9999px;height:50px}
ul#menu li#home a{background-position:0px 0px}
ul#menu li#about a{background-position:-150px 0px}
ul#menu li#services a{background-position:-300px 0px}
ul#menu li#contact a{background-position:-450px 0px}

ul#menu li a span {background:url("images/menu.png");height:50px;display:block}
ul#menu li#home a span{background-position:0px -50px}
ul#menu li#about a span{background-position:-150px -50px}
ul#menu li#services a span{background-position:-300px -50px}
ul#menu li#contact a span{background-position:-450px -50px}

jQuery:

$(function() {
       $("ul#menu li a").wrapInner("<span></span>");
       $("ul#menu li a span").css({"opacity" : 0});

       $("ul#menu li a").hover(function(){
               $(this).children("span").animate({"opacity" : 1}, 400);
       }, function(){
               $(this).children("span").animate({"opacity" : 0}, 400);
       });
});