John
John

Reputation: 11

Jquery change class on click menu

I am trying to change the class of a menu item so that it appears on click. I have got it to work, the only thing it does not revert back when you click it again. I am not sure how to remove the class on click.

All help is much appreciated.

   <!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <style>
  .menu ul li ul li {display:none}
  .menu .on ul li{display:block}
  .menu .on ul li ul{display:none}
  .menu .on ul li:hover ul{display:block}
  </style>
</head>
<body>
<div class="menu">
<ul>
  <li><a href="#">Toggle</a>
  <ul>
  <li>See</li></ul></li>
  <li><a href="#">Toggle</a>
  <ul>
  <li><a href="#">See</a>
  <ul><li><a href="#">See 2</a></li></ul></li></ul></li>
  </ul>
  </div>


<script>
$('li a').click(function() {
  $(this).parent().addClass('on').siblings().removeClass('on');
});

</script>

</body>
</html>

Upvotes: 1

Views: 3954

Answers (2)

FishBasketGordo
FishBasketGordo

Reputation: 23122

Use toggleClass[API Ref] to switch the one you clicked on/off and its siblings off/on, respectively:

$('li a').click(function() {
    var parent = $(this).parent();
        siblings = parent.siblings(),
        isOn = parent.toggleClass('on').hasClass('on');

    siblings.toggleClass('on', !isOn);
});

Upvotes: 0

m.edmondson
m.edmondson

Reputation: 30862

You need toggleClass()

Upvotes: 3

Related Questions