1

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>
1
  • your HTML is incorrect (you have a <ul> without closing a <li>). You should correct it if you want your js to work Commented Sep 12, 2011 at 14:24

2 Answers 2

3

You need toggleClass()

Sign up to request clarification or add additional context in comments.

1 Comment

Hi toggleClass worked $('li a').click(function() { $(this).parent().toggleClass('on').siblings().removeClass('on'); });
0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.