Sunday, May 16, 2010

Creating a smooth sliding horizontal menu using JQuery

For this example we need the latest version of Jquery which is available at http://Jquery.com
here goes our HTML Code:
and the CSS:
#slider{
height:122px;
clear:both;
margin:30px 10px 10px;
background:#E6F1FE;}

#slider ul{
list-style-type:none;
height:122px;
overflow:hidden;}

#slider ul li{
display:inline;
float:left;
width:122px;}

#slider ul li a:hover{
cursor:pointer;}

#homeSlider ul li img{
display:block;
float:left;
border:solid 1px #2B78B0;}

#slider .current{
width:500px;}
Now here comes the magic(JQuery!!)
You are just 5 lines away from creating a smooth sliding Horizontal menu.
$(document).ready(function(){
var minWidth = 122;
var maxWidth = 500;
$(”#slider ul li”).hover(function(){
$(”#slider ul li”).animate(
{width:minWidth+”px”},{queue:false,duration:”slow” }
);
$(this).animate(
{width:maxWidth+”px”},{queue:false,duration:”slow” }
);
});

Now lets understand the JQuery code
1) $(“#slider ul li”).hover(function(){
-> this line binds hover event to all the LI elements after the DOM is loaded
2) $(“#slider ul li”).animate({width: minWidth +“px”}, { queue:false, duration:“slow” });
-> In above line we are animating the width of all the LI elements to minWidth with slow transition and making the queue false as we have to make width of the hovered LI element to maxWidth.
3) $(this).animate({width: maxWidth +“px”}, { queue:false, duration:”slow” });
-> In above line $(this) refers to the hovered element, we are animating the width of the hovered element to max width a slow transition as to create a smooth effect.

Thats it, with this you should be able to create a smooth horizontal menu with JQuery..

Bye for now… be updated to my blog as there are many more to come :)

No comments:

Post a Comment