Using jQuery For The Animation

The animation is really quite simple. We’ll use jQuery to animate the opacity of the <span> tag. Remember that the <span> tag displays the “hover” state of the image. Hence, when the <span> is visible, the link takes the “hover” appearance. We’ll need the “hover” state to be invisible when the page loads. We can do this by setting the opacity of the <span> tag to “0″:

$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// the rest of the code will go here

});

Placing the code inside of “$(function() { … });” tells the browser to execute the code when the document has loaded. The code that we’ll use to do the animation is as follows:

// on mouse over
$("ul#menu span").hover(function () {

// animate opacity to full
$(this).stop().animate({
opacity: 1
}, 'slow');

},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({

opacity: 0
}, 'slow');
});

Hence the entire Javascript used is as follows:

<!-- Include jQuery Library -->

<script src="jquery-1.2.2.pack.js" type="text/javascript"></script>
<!-- Let's do the animation -->
<script type="text/javascript">

$(function() {
// set opacity to nill on page load
$("ul#menu span").css("opacity","0");
// on mouse over
$("ul#menu span").hover(function () {
// animate opacity to full
$(this).stop().animate({
opacity: 1
}, "slow");
},
// on mouse out
function () {
// animate opacity to nill
$(this).stop().animate({
opacity: 0
}, "slow");
});
});
</script>

Notice that we first include the jQuery library. You can learn more about jQuery animations by reading up on the documentation. One final addition to the CSS is required to ensure that the mouse cursor is display as a pointer when hovering over the <span> tag:

ul#menu li a span:hover {
cursor:pointer;

}

The full source code can be accessed via the demonstration page. I should just add that whilst this code seems to work well with FireFox and IE7, IE6 might (and probably will) be a different story.

If you have better solution, just tell me !

0 comments: