2

I have the code html

<div class="mobile"></div>
    <ul id="nav">
        <li><a href="index.php">Home</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="work.php">Work</a></li>
        <li><a href="contact.php">Contact</a></li>
    </ul>
</div>

I need to: On click add class to the ul

<div class="mobile"></div>
    <ul id="nav" class="visible">
        <li><a href="index.php">Home</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="work.php">Work</a></li>
        <li><a href="contact.php">Contact</a></li>
    </ul>
</div>

I've tried:

jQuery(document).ready(function() {
    jQuery('.mobile').click(function(){
        jQuery('#nav').removeClass('selected')
        jQuery('#nav').addClass('selected');
    });
});

When I click the first time the js add the class selected as I want; but when I click again it does nothing, it should remove that class, but it doesn't work. How can I do this?

Does anyone know the answer to this?

1
  • Just a note: jQuery('#nav').removeClass('selected') is missing a ; in the end of the line. Commented Jan 30, 2013 at 11:58

3 Answers 3

1

use toggleClass():

jQuery(document).ready(function() {
    jQuery('.mobile').click(function(){
         jQuery('#nav').toggleClass('selected');
    });
});

Although its not clear to me you want visible class or selected class.

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

Comments

1

What you do in your code is that everytime you click you remove and add the class. Hence it stays added after the first click. You can do this to get the desired behaviour:

$(document).ready(function() {
    $('.mobile').click(function(){
        $('#nav').toggleClass('selected');
    });
});

Comments

0

What do you want actually. If you want to add the class, on clicking for more than one time, the class gets adding. If you want to add if the class is not added and remove if the class is already added for the each click then the below code should work.

$('.mobile').click(function() {
   $('#nav').toggleClass('selected');
});

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.