Search

Slide out and drawer effect

Posted on 6th January 2008 — John Resig, author of jQuery demonstrated how easy is create this simple slide aka drawer aka accordion effect during @media Ajax 2007 - it also makes for a great introduction to jQuery.

The effect is commonly known as an ‘accordion’ and it’s usually used to slide up, or down blocks of content to expose new blocks.

Apple downloads drawer sample

The Apple web site is a great demonstration of this effect in action, where the mouse settles on the title of the ’section’ and the associated links are exposed. What makes this effect particularly cool, is that the drawers maintain a fixed height and slide between restricted area.

This tutorial will walk through how to create your own simple plugin, and then replicate the Apple downloads drawers using the very excellent Accordion plugin.

Markup

Since we’re practising unobtrusive JavaScript, the markup will start with headings separating the list items.

There’s two approaches depending on your content. Either to use list elements or definition lists. Our example will use list elements.

<ul class="drawers">
  <li class="drawer">
    <h2 class="drawer-handle open">Downloads</h2>
      <ul>
        <!-- list items -->

And so on, with as many drawer elements as we want. Note that in this example, the ‘open’ class has only been applied to the first drawer.

Simple jQuery slide effect

In it’s simplest form, the effect is this when the user clicks on the drawer handle:

  1. Hide all the drawer content elements
  2. Show the drawer content associated with the current drawer handle

In addition, when the page loads, we should hide all the drawer content, except for our starting point.

This is achieved with the following code:

$(document).ready(function () {
  // hide all ULs inside LI.drawer except the first one
  $('LI.drawer UL:not(:first)').hide(); 
  
  // apply the open class
  $('LI.drawer UL:first').addClass('open');
  
  $('H2.drawer-handle').click(function () {
    // hide the currently visible drawer contents
    $('LI.drawer UL:visible').hide();
    
    // remove the open class from the currently open drawer
    $('H2.open').removeClass('open');
    
    // show the associated drawer content to 'this' (this is the current H2 element)
    // since the drawer content is the next element after the clicked H2, we find
    // it and show it using this:
    $(this).next().show();
    
    // set a class indicating on the H2 that the drawer is open
    $(this).addClass('open');
  });
});

If you wanted to make better using of jQuery’s chaining the code could be written as this:

$(function () { // same as $(document).ready(function () { })
  // assuming we have the open class set on the H2 when the HTML is delivered
  $('LI.drawer H2:not(.open)').next().hide();

  $('H2.drawer-handle').click(function () {
    // find the open drawer, remove the class, move to the UL following it and hide it
    $('H2.open').removeClass('open').next().hide();
    
    // add the open class to this H2, move to the next element (the UL) and show it
    $(this).addClass('open').next().show();
  });
});

If you want it to slide, we can easily swap .hide() for .slideUp() and .show() for .slideDown(), as I have done in the working example of the simple slide demo

If you look at the demo, for me, the annoying aspect is that the height changes depending on which drawer you’ve got open. In particular, if you have the first drawer open, and click on the second, the position of the third drawer handle moves up.

That’s where the accordion plugin helps us.

jQuery accordion plugin

Using the same markup as the previous example, if we take Jörn Zaefferer’s Accordion plugin we can match the effect on Apple’s site.

Before we can use the plugin however, there are a few prerequisites: in particular, you must have the dimensions plugin. The best place to get the latest files is the plugin repository for Accordion. Download the zip file (using the link towards the foot of the page) and grab the following files:

  • jquery.accordion.js (or the packed versions)
  • lib/jquery.js (if you’ve not got the library already)
  • lib/jquery.dimensions.js

Again, using our existing markup, we can use the following code to get the plugin working straight away:

<script src="jquery.js" type="text/javascript"></script>  
<script src="jquery.dimensions.js" type="text/javascript"></script>  
<script src="jquery.accordion.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
$(function () {
  $('UL.drawers').accordion({
    // the drawer handle
    header: 'H2.drawer-handle',
    
    // our selected class
    selectedClass: 'open',
    
    // match the Apple slide out effect
    event: 'mouseover'
  });
});
-->
</script>

That’s it! Simple and very easy to use so long as you have all the right files.

See the plugin version of the slide out effect

Related posts

Demo

If you find this demo doesn't work as expected, it's possibly due to the demo running from within an iframe. Try running the demo in it's own window.

Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Slide Demo - Fixed Drawer</title>
        <style type="text/css" media="screen">
        <!--
        BODY { margin: 10px; padding: 0; font: 1em "Trebuchet MS", verdana, arial, sans-serif; font-size: 100%; }
        DIV.container { margin: auto; width: 90%; margin-bottom: 10px;}
        TEXTAREA { width: 80%;}
        FIELDSET { border: 1px solid #ccc; padding: 1em; margin: 0; }
        LEGEND { color: #ccc; font-size: 120%; }
        INPUT, TEXTAREA { font-family: Arial, verdana; font-size: 125%; padding: 7px; border: 1px solid #999; }
        LABEL { display: block; margin-top: 10px; } 
        IMG { margin: 5px; }

        h2 {
            margin: 0;
        }

        .drawers-wrapper {
            position: relative;
            width: 188px;
            
        }

        .drawer {
            background:transparent url(http://images.apple.com/downloads/images/sideboxlight_bg20070611.gif) repeat-y scroll 0pt;
            color:#76797C;
            font-size:11px;
            line-height:1.3em;
        }

        .boxcap {
            height:5px;
            left:0pt;
            position:absolute;
            width:100%;
            z-index:100;
            background:transparent url(http://images.apple.com/downloads/images/sidenav_capbottom.png) no-repeat scroll 0%;
            margin-top:-5px;
        }

        .captop {
            background-image:url(http://images.apple.com/downloads/images/box_188captop.png);
            bottom:auto;
            top:0pt;
            margin-top:0;
        }

        .drawers {
            margin-bottom:15px;
            color:#76797C;
            font-size:11px;
            line-height: 18px;
        }

        .drawers A {
            color:#666666;
            text-decoration:none;
            font-family:"Lucida Grande",Geneva,Arial,Verdana,sans-serif;
            font-size-adjust:none;
            font-style:normal;
            font-variant:normal;
            font-weight:normal;
        }

        .drawer li {
            border-bottom:1px solid #E5E5E5;
            line-height:16px;
            padding:6px 0pt;
        }

        UL {
            list-style: none;
            padding: 0;
        }

        UL.drawers {
            margin: 0;
        }

        .drawer-handle {
            background:#939393 url(http://images.apple.com/downloads/images/slider_handlebg188.png) no-repeat scroll 0pt;
            color:#333333;
            cursor:default;
            font-size:12px;
            font-weight:normal;
            height:25px;
            line-height:25px;
            margin-bottom:0pt;
            text-indent:15px;
            width:100%;
        }

        .drawer-handle.open {
            background-color:#72839D;
            background-position:-188px 0pt;
            color:#FFFFFF;
        }

        .drawer UL {
            padding: 0 12px;
            padding-bottom:0pt;
        }

        .drawer-content UL {
            padding-top: 7px;
        }

        .drawer-content LI A {
            display:block;
            overflow:hidden;
        }

        .alldownloads li {
            border:0pt none;
            line-height:18px;
            padding:0pt;
        }
        -->
        </style>

    <script src="jquery-1.2.1.js" type="text/javascript"></script>
    <script src="jquery.dimensions.js" type="text/javascript"></script>
    <script src="jquery.accordion.js" type="text/javascript"></script>

    <script type="text/javascript">
    <!--
    $(function () {
        $('ul.drawers').accordion({
            header: 'H2.drawer-handle',
            selectedClass: 'open',
            event: 'mouseover'
        });
    });
    //-->    
    </script>
</head>
<body id="page">
    <h1>Fixed drawer slide out demo (using accordion plugin)</h1>
    <p>This example demonstrates the Apple downloads slider/accordion effect using the jQuery Accordion plugin.</p>
    <p>Mouse over the headings to reveal the list of available links.</p>

    <p><a href="http://jqueryfordesigners.com/slide-out-and-drawer-effect/">Read the article this demonstration relates to</a></p>
    <div class="drawers-wrapper">
	<div class="boxcap captop"></div>
    <ul class="drawers">
        <li class="drawer">
            <h2 class="drawer-handle open">Downloads</h2>
            <ul class="alldownloads">
                <li id="sn-downloadsmacosx"><a href="/downloads/macosx/">All Categories</a></li>
                <li id="sn-aperture"><a href="/downloads/macosx/aperture/">Aperture</a></li>
                <li id="sn-apple"><a href="/downloads/macosx/apple/">Apple</a></li>
                <li id="sn-audio"><a href="/downloads/macosx/audio/">Audio</a></li>
                <li id="sn-automator"><a href="/downloads/macosx/automator/">Automator Actions</a></li>
                <li id="sn-businessfinance"><a href="/downloads/macosx/business_finance/">Business &amp; Finance</a></li>
                <li id="sn-calendars"><a href="/downloads/macosx/calendars/">Calendars</a></li>
                <li id="sn-developmenttools"><a href="/downloads/macosx/development_tools/">Development Tools</a></li>
                <li id="sn-drivers"><a href="/downloads/macosx/drivers/">Drivers</a></li>
                <li id="sn-emailchat"><a href="/downloads/macosx/email_chat/">Email &amp; Chat</a></li>
                <li id="sn-finalcutstudio"><a href="/downloads/macosx/finalcutstudio/">Final Cut Studio</a></li>
                <li id="sn-games"><a href="/downloads/macosx/games/">Games</a></li>
                <li id="sn-homelearning"><a href="/downloads/macosx/home_learning/">Home &amp; Learning</a></li>
                <li id="sn-iconsscreensavers"><a href="/downloads/macosx/icons_screensavers/">Icons, Screensavers, etc.</a></li>
                <li id="sn-imaging3d"><a href="/downloads/macosx/imaging_3d/">Imaging &amp; 3D</a></li>
                <li id="sn-internetutilities"><a href="/downloads/macosx/internet_utilities/">Internet Utilities</a></li>
                <li id="sn-ipoditunes"><a href="/downloads/macosx/ipod_itunes/">iPod + iTunes</a></li>
                <li id="sn-mathscience"><a href="/downloads/macosx/math_science/">Math &amp; Science</a></li>
                <li id="sn-networkingsecurity"><a href="/downloads/macosx/networking_security/">Networking &amp; Security</a></li>
                <li id="sn-productivitytools"><a href="/downloads/macosx/productivity_tools/">Productivity Tools</a></li>
                <li id="sn-spotlight"><a href="/downloads/macosx/spotlight/">Spotlight Plugins</a></li>
                <li id="sn-systemdiskutilities"><a href="/downloads/macosx/system_disk_utilities/">System/Disk Utilities</a></li>
                <li id="sn-unixopensource"><a href="/downloads/macosx/unix_open_source/">UNIX &amp; Open Source</a></li>
                <li id="sn-video"><a href="/downloads/macosx/video/">Video</a></li>
                <li id="sn-dashboard"><a href="/downloads/dashboard/" class="bottom">Widgets</a></li>
            </ul>
        </li>
        <li class="drawer">
            <h2 class="drawer-handle">Top Downloads</h2>
            <ul>
                <li><a title="iTunes 7.5" href="http://www.apple.com/itunes/download/">1. iTunes 7.5</a></li>
                <li><a title="QuickTime 7.3.1" href="http://www.apple.com/quicktime/download/">2. QuickTime 7.3.1</a></li>
                <li><a title="Safari 3 Public Beta" href="http://www.apple.com/safari/download/">3. Safari 3 Public Beta</a></li>
                <li><a title="MacPool" href="/downloads/macosx/games/simulation_and_sports/macpool.html">4. MacPool Realistic and easy to play computer simu…</a></li>
                <li><a title="Guitar Hero III: Legends of Rock" href="/downloads/macosx/games/demos_updates/guitarheroiiilegendsofrock.html">5. Guitar Hero III: L…</a></li>
                <li><a title="Messenger for Mac" href="/downloads/macosx/email_chat/messengerformac.html">6. Messenger for Mac</a></li>
                <li><a title="Google Earth" href="/downloads/macosx/home_learning/googleearth.html">7. Google Earth</a></li>
                <li><a title="Monopoly" href="/downloads/macosx/games/cards_puzzle/monopoly.html">8. Monopoly</a></li>
                <li><a title="Litho System Icons" href="/downloads/macosx/icons_screensavers/lithosystemicons.html">9. Litho System Icons</a></li>
                <li><a title="Battlefield 2142" href="/downloads/macosx/games/demos_updates/battlefield2142.html">10. Battlefield 2142</a></li>
                <li><a title="More iChat Effects" href="/downloads/macosx/email_chat/moreichateffects.html">11. More iChat Effects</a></li>
                <li><a title="Dragster" href="/downloads/macosx/internet_utilities/dragster.html">12. Dragster</a></li>
                <li><a title="iSquint" href="/downloads/macosx/ipod_itunes/isquint.html">13. iSquint</a></li>
                <li class="last"><a title="US Holiday Calendar" href="/downloads/macosx/calendars/usholidaycalendar.html">14. US Holiday Calendar</a></li>
            </ul>
        </li>
        <li class="drawer last">
            <h2 class="drawer-handle">Top Apple Downloads</h2>
            <ul>
                <li><a title="iTunes 7.5" href="http://www.apple.com/itunes/download/">1. iTunes 7.5</a></li>
                <li><a title="QuickTime 7.3.1" href="http://www.apple.com/quicktime/download/">2. QuickTime 7.3.1</a></li>
                <li><a title="Safari 3 Public Beta" href="http://www.apple.com/safari/download/">3. Safari 3 Public Beta</a></li>
                <li><a title="Mac OS X 10.5.1 Update" href="/downloads/macosx/apple/macosx_updates/macosx1051update.html">4. Mac OS X 10.5.1 Up…</a></li>
                <li><a title="Java for Mac OS X 10.4 Release 5" href="/downloads/macosx/apple/macosx_updates/javaformacosx104release5.html">5. Java for Mac OS X …</a></li>
                <li><a title="iPod Reset Utility 1.0.2 for Windows" href="/downloads/macosx/apple/ipod_itunes/ipodresetutility102forwindows.html">6. iPod Reset Utility…</a></li>
                <li><a title="iPhoto 7.1.1" href="/downloads/macosx/apple/application_updates/iphoto711.html">7. iPhoto 7.1.1</a></li>
                <li><a title="Bonjour for Windows" href="/downloads/macosx/apple/windows/bonjourforwindows.html">8. Bonjour for Windows</a></li>
                <li><a title="Mac OS X 10.4.11 Combo Update (PPC)" href="/downloads/macosx/apple/macosx_updates/macosx10411comboupdateppc.html">9. Mac OS X 10.4.11 C…<br/>The 10.4.11 Update is recommended for al…</a></li>
                <li><a title="Java for Mac OS X 10.4, Release 6" href="/downloads/macosx/apple/macosx_updates/javaformacosx104release6.html">10. Java for Mac OS X …</a></li>
                <li><a title="GarageBand 4.1.1" href="/downloads/macosx/apple/application_updates/garageband411.html">11. GarageBand 4.1.1</a></li>
                <li><a title="iPod Updater 2006-06-28 for Windows" href="/downloads/macosx/apple/ipod_itunes/ipodupdater20060628forwindows.html">12. iPod Updater 2006-…</a></li>
                <li><a title="Security Update 2007-009 1.1 (10.4.11 Universal)" href="/downloads/macosx/apple/security_updates/securityupdate20070091110411universal.html">13. Security Update 20…</a></li>
                <li class="last"><a title="Security Update 2007-009 1.1 (10.5.1)" href="/downloads/macosx/apple/security_updates/securityupdate2007009111051.html">14. Security Update 20…</a></li>
            </ul>
        </li>
    </ul>
	<div class="boxcap"></div>
	</div>
</body>
</html>

Comments

  1. Artzone On 21st January 2008 at 09:01

    Hey great tutorial. Thanks for sharing this.

    I’ve been looking at the accordion plugin and wondered how I could make it remember which section was open when a link is clicked in that section. Let’s say I have an accordion with 3 sections and I click a link in the second section. The new page loads and my accordion closes or it displays with the first section expanded. I’d really like it to stay open and display the links in the second section. Any thoughts on the best way of doing this?

    Cheers Art

  2. john cooper On 21st January 2008 at 16:01

    Finally someone explaining how to use jQuery for simpletons like myself. Also showing the jQuery accordion can work without that annoying bounce effect! :D

  3. RickL On 24th January 2008 at 22:01

    Has anyone else taken a look at the plugin version page in IE? There are problems…

  4. Remy On 25th January 2008 at 01:01

    @RickL - I see what you’re saying. There’s an IE6 specific issue with the CSS.

    The actual plugin isn’t broken, you can still roll over - it’s just the colouring on the background looks strange. The styling was fairly complicated from the Apple web site, so it’s no wonder it didn’t drop in to IE6 perfectly - sorry!

  5. ajaxlearner On 1st February 2008 at 00:02

    Hi, I tried to copy the source code on the demo page and try to run it as sample web application. It opens out all drawers and keeps them that way. The accordian effect is missing. Please help how i may have gone wrong.

  6. Remy On 19th February 2008 at 01:02

    @ajaxlearner - without seeing your code, I’m having to guess, but if I were to guess, I would say that the ID is missing on the element that plays as the accordion - or doesn’t match the ID used in the jQuery selector.

  7. Boz On 23rd February 2008 at 18:02

    Does not work with latest version of accordian plugin. Revision: $Id: jquery.accordion.js 2880 2007-08-24 21:44:37Z Works OK with the plugin used in the demo.

  8. Loren Helgeson On 25th February 2008 at 20:02

    It’s an excellent demo. Looks very promising. Only problem is that it doesn’t work correctly in Safari, which is definitely ironic. The drawer tabs change, but the content disappears, and there is no slider effect.

  9. Remy On 26th February 2008 at 00:02

    @Loren - I’ve just looked at my logs and can see you’re on the very latest Safari (WebKit 523.12.2) - I’ve not upgraded to 10.5.2 yet, as such, the effect is fine on my machine (though I’ll be upgrading this evening).

    I’ll raise a bug with the jQuery UI guys if it’s the plugin, or fix my code if it’s on my side once I’m on the same version.

    Thanks for the heads up.

  10. Geoff On 3rd March 2008 at 13:03

    Hey guys have managed to get this script working perfectly in all browsers

    Had an issue where the content within the li would be overlapping the other sections when the animation ran, (ie 6+7) and also had an issue in ie6 where the background for the li wasn’t showing.

    with a little bit of css tinerking im sure the guys above should be able to resolve their browser specific issues also.

    Nice work Remy

  11. Matt On 24th March 2008 at 20:03

    @Geoff - Can you share any of the css you’ve done to get this working well across the various browsers? I’ve got most of it OK but still a few problems with ie5. I used the iepngfix.htc from http://www.twinhelix.com which helped.

    Cheers Matt

  12. Bernd Matzner On 27th March 2008 at 15:03

    Hi,

    In the demo posted here, if I move my mouse to the third item, the second is opened and nothing happens.

    Last year, I published a draft for an accordion plugin that includes similar functionality, and uses Brian Cherne’s hoverIntent plugin to detect if the user’s mouse comes to a stop over an accordion section, so only the section the mouse is moved to opens up instead of every section the mouse crosses.

    See my site for samples: http://berndmatzner.de/jquery/hoveraccordion/

    Bernd

  13. Waiton On 11th April 2008 at 11:04

    Hi there.

    Thanks so much for sharing this with us. With regard to the Accordian version, I’ve got most of it working and it works splendidly on IE6, but (believe it or not) on Firefox 2.0.0.13 and Safari 3.1, the li items in the preceding list overlaps with the heading of the list below them.

    Click on the gallery part of the site - it only happens the first time you load the gallery page though. And I’ve only got filler content on the first list so that’s the only one that’s breaking at the moment.

    http://www.digitaleasel.co.nz/gallery.php

    I’ve tried to simulate the problem by swapping in the code from the sample page and the problem is not repeated. I would use this code instead but I’m a novice and don’t know how to change it so that you don’t have to click the list header to open the list. You can see this at http://www.digitaleasel.co.nz/gallery2.php

    Any help would be great, but no worries if everyone’s busy :) Hopefully you can see the code (I have the Web Developer Firefox add-on) - if not, I’ll be happy to send it to someone.

    Cheers!

  14. Isko On 11th April 2008 at 16:04

    Great tutorial! I’m new to jQuery but tutorials like this are excellent way to learn and start using more jQuery.

    I was wondering if there’s a quick solution for a question I have concerning the simple slide demo. Is it possible to close the already opened drawer? Right now, if you click the open drawer, it closes and opens again. It would be more logical if it would just close the open drawer.

    I tried to play around with the code but didn’t have much luck..

  15. Christopher Webb On 15th April 2008 at 03:04

    I’ve noticed that the open drawers seem to open as wide as the tallest element within a drawer. For instance, drawer #1 has 2 lines of content and drawer #2 has 10 lines of content, but drawer #1 opens with 2 lines of content and 8 lines of empty space. Is there anyway to get them to open to their own specific sizes regardless of how big or small the others are?

  16. Chris On 16th April 2008 at 22:04

    Excellent demo! I hope this trend of showing real world examples continues. I plan on using this in a template I’m building, and eventually make it into a plugin or module. Thanks a lot!

  17. Paul @ Web Design Ireland On 7th May 2008 at 13:05

    @ Art - you can use a property on the jscript to keep it open at certain sections

    $(function () { $(’ul.drawers’).accordion({ header: ‘H2.drawer-handle’, selectedClass: ‘open’, event: ‘mouseover’, active: ‘.open’ }); });

  18. owen On 3rd July 2008 at 19:07

    sabes alguna manera o forma de poner la cabecera del accordion en la parte de abajo????

    es decir que el cuerpo se expanda hacia arriba!!!

    res. a email por favor

  19. Nicole On 19th July 2008 at 23:07

    Is it possible to make the bottom, or last, list item appear open by default, rather than the first? I am using this for a list that only contains two items (or, drawer handles). As such, it looks kind of odd with one handle at either end. I’d rather have both handles at the top of the element when the user refreshes the screen. I hope that makes sense!

    Thanks for putting this code out there - it looks and works great! Nicole

  20. e-hadi On 31st July 2008 at 23:07

    wawwww Supperr. Thanks. God..

  21. joshuaxu On 11th August 2008 at 14:08

    it can’t work with the last version jquery

  22. Kyle On 11th August 2008 at 19:08

    Anyway to do custom speeds on slide or delays on hover? I’m getting complaints that it is a little too fast.

    Check the site - thanks!

  23. Tyler On 2nd September 2008 at 14:09

    Hi! I have got a problem on ie6. I got an extra space under the Accordion. The height seems to be linked to the number of items in the Accordion.. very strange. I try to manage the css, but nothing. I don’t want to put a fix height to the container as the content could increase. Does anyone knows this bug for ie6?

    thanx for help :)

  24. Chaitanya On 4th September 2008 at 16:09

    The length of the drawer is not changing dynamically if the content in the drawer is dynamic. so I am not able to see whole content even though it is there..

    Any ideas..

    Thanks.

  25. Waqas Khalid On 19th September 2008 at 03:09

    In IE 6.0, Its not showing the same behaviour as it is showing in FF 3.x and opera. colors are changed in bad way and spacing as described by Tyler on 2nd Sept is also disturbed. for FF3.x and Opera, its marvelous !!

Leave your own comment
  • http://