22 December 2015

Create a click/tap dropdown menu from a simple nested list

Here’s a bit of jQuery for creating a simple click/tap triggered custom dropdown menu from a nested list.

Assuming your HTML looks like this:

Your jQuery should look like this:

What’s going on here?

First, we detect where the user clicks (‘html’ in this case, i.e. anywhere within the browser window):

If the target area’s immediate parent has a ‘menu-item-has-children’ class, we disable its default action (i.e. we prevent it from functioning as a link):

And secondly we add an ‘open’ class to the target’s parent, to which we can assign some pretty CSS to display our newly opened dropdown:

Meanwhile at the top of our function we remove the ‘open’ class from all parent menu elements in case there are any other dropdowns already open:

And that’s it. View the working demo.