saltcod
saltcod

Reputation: 2031

Toggle menu items

I want to toggle a class on a menu item when I click it, to reveal an attached sub-menu. I need the toggle to happen when you click an item on/off, but also when you click another menu item, it needs to toggle itself on and the already open one off.

Pen here: http://codepen.io/saltcod/pen/rxZwBZ?editors=1100

 ( function( window, $ ) {
'use strict';

var primaryNavLinks = document.querySelectorAll('.primary-navigation > .menu > li > a');

_.each( primaryNavLinks, function( primaryNavLink ) {

    // add event listener to each menu item
    primaryNavLink.addEventListener( 'click', function() {

        // if one already has class 'open', remove it
        if ($(primaryNavLinks).hasClass('open') ) {
            $( primaryNavLinks ).removeClass('open');
        }

        // toggle 'open' on the one that we've clicked

        $(this).toggleClass('open');

    });
});

} )( this, jQuery );
<nav class="primary-navigation" role="navigation">
<ul class="menu">
    <li>
          <a href="#">News</a>
              <div class="sub-menu">
                  <div class="wrapper">
                        <ul>
                              <li><a href="#">All News</a></li>
                                <li><a href="#">This other news</a></li>
                                <li><a href="#">More news</a></li>
                        </ul>
                </div>
            </div>
      </li>
      <li><a href="#">Weather</a></li>
      <li><a href="#">Sports</a></li>
      <li><a href="#">Live</a></li>
</ul>

It's 99% working now — when I click an item it toggles on, when I click another it toggles that one on. The part that isn't working is when I click an item it won't toggle itself closed.

Thanks!

ps: I'm using a bit of a mixture of vanilla and jQuery.

Upvotes: 0

Views: 259

Answers (2)

brs14ku
brs14ku

Reputation: 346

(function(window, $) {
  'use strict';

  var primaryNavLinks = $('.primary-navigation .menu li a');
  primaryNavLinks.click(function(e) {
    e.preventDefault();

    if( $(this).hasClass('open') ) {
       primaryNavLinks.removeClass('open');
    }else{
      primaryNavLinks.removeClass('open');
      $(this).addClass('open');
    }
 });

})(this, jQuery);

Got this working in your codepen. Give it a try.

Upvotes: 1

jsxsl
jsxsl

Reputation: 200

If you want to toggle 'off' or close the item you clicked then you don't want to call the toggle 'open' function again. Below I only call the toggle('open') if the link is not open.

  // if one already has class 'open', remove it
  if ($(primaryNavLinks).hasClass('open')) {
      $(primaryNavLinks).removeClass('open');
  } else {
      // toggle 'open' on the one that we've clicked
      $(this).toggleClass('open');
  }

Upvotes: 1

Related Questions