top_menu

Tuesday, 30 August 2011

Facebook style drop down menu using jquery and css

.

Drop down menus are becoming more popular because of their compactness and user interactivity. Now a days they are being adopted by many modern websites like facebook, gmail, google+, orkut, yahoo...

In this tutorial we will create a similar drop down menu which is easy to integrate into any website.

facebook drop down menu using css and jquery

       

The HTML

<div style="width:162px;">
 <dl style="" class="menu">
    <dt>
    <a class="" id="linkglobal" 
    style="cursor: pointer;"></a><span class="result"></span></dt>
    <dd>
  <ul style="display: none;" id="ulglobal">
    <li><a href="#">Everyone</a></li>
    <li><a href="#">Friends</a></li>
    <li><a href="#">Only Me</a></li>
    <li><a href="#">Customize</a></li>
   </ul>
    </dd>
 </dl>
</div>

The CSS

<style type="text/css">
.menu dl{ margin-left:5px; }
.menu dd, .menu dt, .menu ul 
{ margin:0px; padding:0px; }
.menu dd { position:relative; }


.menu dt a {background:#EEEEEE 
url(privacyOff.png) no-repeat scroll right center;
 display:block; width:40px; height:22px; cursor:pointer;}

.menu dt a.selected{
 background:#EEEEEE url(privacyOn.png) 
 no-repeat scroll right center;
}
.menu dt a span {
cursor:pointer; display:block; padding:5px;}

.menu dd ul { 
background:#EEEEEE none repeat scroll 0 0; display:none;
 list-style:none; padding:3px 0; position:absolute;
 left:0px; width:160px; left:auto; right:0; 
 border:1px solid #656565; cursor:pointer;
 }
.menu dd ul li{ 
background-color:#EEEEEE; margin:0; width:160px;
}
.menu span.value { display:none;}
.menu dd ul li a { 
display:block; font-weight:normal; width:137px; 
text-align:left; overflow:hidden; padding:2px 4px 3px 19px; 
color:#111111; text-decoration:none;
}
.menu dd ul li a:hover{ 
background:#656565; color:white; text-decoration:none; 
}
.menu dd ul li a:visited{ 
text-decoration:none; 
}
</style>

The jQuery which adds the user interactivity


<script type="text/javascript">

$(document).ready(function(){



// This hides the menu when the page is clicked anywhere other than the menu.

$(document).bind('click', function(e) {

var $clicked = $(e.target);

if (! $clicked.parents().hasClass("menu")){

 $(".menu dd ul").hide();

 $(".menu dt a").removeClass("selected");

}



});



$(".menu dt a").click(function() {

var clickedId = "#" + this.id.replace(/^link/,"ul");



 // Hides everything else that the current menu

$(".menu dd ul").not(clickedId).hide();



 //Toggles the menu.

$(clickedId).toggle();



 //Add the selected class.

if($(clickedId).css("display") == "none"){

 $(this).removeClass("selected");

}else{

 $(this).addClass("selected");

}

});



// This function shows which menu item was selected in corresponding result place

$(".menu dd ul li a").click(function() {

var text = $(this).html();

$(this).closest('dl').find('.result').html(text);

$(".menu dd ul").hide();

});

});

</script>