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

JavaScript

jQuery Collapsible Navigation

Hi all,

I'm trying to build a basic collapsible navigation menu, without using the Bootstrap components (I want to test my skills). I have a simple <ul> nav which is followed by a hamburger menu icon. I am using jQuery to hide the nav and, when the menu icon is clicked, the nav is shown and the hamburger turns into an 'X' icon. When the 'X' icon is clicked, the nav is hidden once again. I have managed to create this without issue, but the .click() function is only working once - after the nav has been hidden by clicking the 'X', clicking on the menu icon does not show the nav again. My code is as follows:

<nav id="header_nav">
     <ul>
            <li><a href="#">Services</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Work</a></li>
            <li><a href="#">Partners</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">Contact</a></li>
     </ul>
</nav>
<a href="#" id="menu"><img src="img/menu.svg" alt="Menu icon" /></a>
// Hide #header_nav initially
$("#header_nav").hide();

// Hamburger icon, onclick
$("#menu").click( function() {
  // Show #header_nav
  $("#header_nav").show();
  // Hamburger icon becomes X icon
  $(this).html("<img src='img/x.svg' alt='X icon' />");
  // X icon, onclick
  $(this).click( function() {
    // Hide #header_nav
    $("#header_nav").hide();
    // X icon becomes hamburger icon
    $(this).html("<img src='img/menu.svg' alt='Menu icon' />");
  });
});

Any help in getting this to run repeatedly (whenever the icons are clicked) would be greatly appreciated.

Many thanks, Tom.

1 Answer

Steven Parker
Steven Parker
243,318 Points

This code is replacing the handler on the first click, and then never switching it back. But it would be even better to have only one handler that operates differently based on the current state of the display.

You might also want to make use of the toggle method, so you don't need to keep track of the state at all.