home photos apps about

Toggle Dropdown - jQuery tutorial

Sat 29 November 2008

Most of us even though we may have heard of jQuery, may not have tried their hand at it. probably like me untill sometime ago. This tutorial is really simple for anyone who knows jQuery, but for those who don't it may be interesting enough to get you started.

This tutorials demonstrates how to create toggle dropdowns, like the one in gamil reply button. [ demo & download links at the bottom ]


<div id="droplist">
    <span class="dropper">Go Somewhere</span>
<div class="links">
        <a href="#">Google the great</a>
        <a href="#">Yahoo the not so great</a>

JavaScript - jQuery

//Select the .dropper class - toggles the dropdown
//and add toggle to toggle between 2 states - show & hide
$('#droplist .dropper').toggle(
    //function to show dropdown which clicked once
    function() {
        //select the offsets left and top of the current element
        offset = $(this).offset();
        var x, y;
        //set the top coordinatess for menu
        x = offset.left;
        y = offset.top + $(this).height() + $(this).css('padding');
        //set the coordinates, and show the element
        $('#droplist .links')
            .css( { left:x, top:y } )
    //toggle functionality 2 - hide when clicked again
    function() {
        $('#droplist .links').hide();

And some CSS :

body { font:12px verdana; text-align:left; line-height:20px; }
#droplist .dropper { border:1px solid #CCCCCC; padding:5px; cursor:pointer; }
#droplist .links { display:none; position:absolute; background:#FBFBFB; border:1px solid #CCCCCC; padding:5px;  }
#droplist .links a { display:block; }


$() acts as a css selector, where in you just need to specify which node you would like to select, just the way one would do in css. $(this) is a reference to the the currently active node, so in our case it would indirectly be a reference to #droplist .dropper.

Try using fadeIn() and fadeOut() instead of show() & hide() respectively.
Also other than the display:attribute in the css, you can change anything to suit your need.

Preview : Preview
Download : jquery_toggle.zip [ jquery.js + toggle.html ]