Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress WordPress Theme Development Building Out WordPress Navigation The wp_nav_menu Function

Bruno Bottega
Bruno Bottega
3,900 Points

Can someone link me a video where I can learn how to make a menu like the one on this project using js?

I don't know how to set up a menu like this and I'd like to know if there is a video on Treehouse that teaches how to create it with javascript. It's one of that menus that you click and it expands. Thanks :)

2 Answers

It's only a few lines of JavaScript to get it working. :) Drop this into whatever JS file you want.

// select menu items with children
jQuery('.menu-item-has-children')

// when the item is clicked...
.click(function() {

  // find the sub-menu underneath this list item
  jQuery(this).find('> .sub-menu')

  // and toggle it
  .slideToggle(250);

  // Also, ignore the default action.
  return false;

});

You'll also need to add the first CSS rule I wrote in the answer above:

.sub-menu
{
  display: none;
  position: absolute;
}

This sort of thing is covered heavily by the jQuery Basics course, especially the fourth badge. Despite the badge's name, dropdown menus are used everywhere, not just for smartphones. :)

Hope this helps! And happy coding!

EDIT: Added prevention of default response.

A dropdown? Those are easy in CSS. Drop this code into your stylesheet and see what you get:

.sub-menu
{
  display: none;
  position: absolute;
}

.menu-item-has-children:hover .sub-menu
{
  display: initial;
}

This code should work on any WordPress navigation menus. You may have to tweak these rules to get the exact look you want. Additionally, it will trigger on a hover, not a click. For it to work on a click, you really will need JavaScript.

Bruno Bottega
Bruno Bottega
3,900 Points

Thanks, Ryan, this helps a lot! But I really need it to work on a click :( Do you know some course around here that teaches an easy way to make it work? By the way: yeah, "dropdown", I was having trouble to remember the correct name.