Drop Down Menus

Written on 2012-11-13 • conversation

Drop down menus. The Information Architect’s nightmare, a Designer’s solution to a cluttered interface. Sometimes you can, sometimes you better not. But when you do, you want to make sure that your menu drops down following a user action.

That last bit is important. Hovering an element with your mouse cursor is not interaction, it is a state of being. Like walking down the street. Imagine every door opening when you walk past it. That would be pretty annoying.

The Drop Down Menu Done Right

Sure, I have used the hover technique in the past myself. When touch interfaces weren’t even an option to consider. But today, they are. And it becomes all the more clear that :hover is not an intended user interaction. So when I really need them, my solution for now is to toggle them on and off with JavaScript following an onClick event.

I want my dropdowns to be accessible, fast and usable. And I hate expanded menus that suddenly collapse because a script has finally loaded. So the first thing I do is put this inline script in the <head> section of my document, before any other script or CSS reference:

<script>document.documentElement.className += " js";</script>

That tiny piece of code adds a class called js to the <html> element. This class is immediately available to hook other scripts or CSS on. The benefits?

  1. You make sure JavaScript is available when hiding the drop down menu via CSS on document load, which is pretty important for accessibility reasons.
  2. There will not be any visible reflows of your drop down menu on document load because the class is applied before loading and applying CSS.

My HTML looks like this:

<ul>
    <li class="has-dropdown is-collapsed">Main Menu Item
        <ul class="dropdown">
            <li>Subitem</li>
            <li>Subitem</li>
            <li>Subitem</li>
        </ul>
    </li>
</ul>

And my CSS for hiding/showing the menu looks like this:

.js .is-collapsed .dropdown {
    position: absolute;
    top: -9999px
}
.js .is-expanded .dropdown {
    position: static;
}

Finally, I toggle the class via JavaScript. It looks like this in jQuery:

$('.has-dropdown').bind('click touchstart', function () {
    $(this).toggleClass('is-expanded').toggleClass('is-collapsed');
});

The result is an accessible, usable, touch-friendly dropdown menu. You now have the force, use it wisely:

Drop Down Menu Demo

Ideas? I’d love to hear them in the comments. Or feel free to react via twitter.

Conversation is closed

Conversations close automatically after six weeks. Feel free to contact me directly if you have feedback on this article.