1

This jquery toggles two things. (1) A css class and (2) displaying a div. The toggle works great if I click outside the element (Menu Toggle), but if I click inside the element itself, the div toggles, but the css class won't. Why is that?

Live preview at http://jsfiddle.net/aL7Xe/68/

I need the added css class to go away when clicking on "Menu Toggle" the second time.

<div id="menuwrap">
 <a href="#" id="menutoggle">Menu Toggle</a>
 <ul id="menucontainer">
    <li><a href="#">One</a></li>
    <li><a href="#">Two</a></li>
    <li><a href="#">Three</a></li>
 </ul>
</div>
this is more text

<script>
$('html').click(function() {
$('#menucontainer').hide();
$('#menutoggle').removeClass('menutoggle');
});

$('#menuwrap').click(function(event){
 event.stopPropagation();
});

$('#menutoggle').click(function(event){
 $('#menucontainer').toggle();
 $(this).addClass('menutoggle');
});
</script>

3 Answers 3

7
$('#menutoggle').click(function(event){
    $('#menucontainer').toggle();
    $(this).toggleClass('menutoggle');
});

http://jsfiddle.net/L5Cq3/

Fewest lines to achieve desired result.

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

Comments

1

Change $(this).addClass('menutoggle'); to $(this).toggleClass('menutoggle');

2 Comments

Hey Juan, I have a a:hover css class set and I want to remove it when you click on the link. I thought it would just be $(this).removeClass('a:hover'); There is a live preview at beattrack.net/test.php. Thanks in advance!
"a:hover" es not actually a class. It is a pseudo class (see w3.org/TR/CSS2/selector.html#dynamic-pseudo-classes). I don't know if there is a pure css solution to what you want. Consider adding a specific class onmouseover the element, and then removing it onmouseout. Then, after the click, just stop adding the class onmouseover.
1

This is because, when you click on the Menu container, both events are fired (i.e. HTML click handler, and the div click handler).

Perhaps this is what you want:

$('#menutoggle').click(function(event){
     $('#menucontainer').toggle();
      if ($(this).hasClass('menutoggle') 
           $(this).removeClass('menutoggle');
       else 
         $(this).addClass('menutoggle');
});

Edit You could just use toggleClass (credits to Juan for reminding me of the existence of that) as well. I'm pretty sure, under the hood, it does the same thing as my code above is doing.

Here's your fixed fiddle: http://jsfiddle.net/aL7Xe/69/

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.