Connor
Connor

Reputation: 71

On click, add/remove class from another div

I am looking to add/remove a class from another div when a link is pressed. I have searched through several answers and searched online but could not find an answer that worked for me.

Here is my code:

<nav id="primary-menu"> <a class="menu-toggle">Browse</a>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">News</a></li>
        <li><a href="#">Rumors</a></li>
        <li><a href="#">Tutorials</a></li>
        <li><a href="#">Miscellaneous</a></li>
    </ul>
</nav> <!-- end #primary-menu -->

I am looking to add the class active to #primary-menu when .menu-toggle is clicked.

For JS/jQuery, I've tried click, toggle, toggleClass, I've tried inlining the code, I've tried external scripts. Nothing seems to work and I'm not sure why.

I'd really appreciate your responses. PS: I'm not the best with JS/jQuery.

Upvotes: 2

Views: 47661

Answers (4)

Tim Hallyburton
Tim Hallyburton

Reputation: 2929

http://jsfiddle.net/te7brkmj/
this combination of 'click' and 'toggleClass' works for me.

$('.menu-toggle').click( function() {
    $("#primary-menu").toggleClass("someClass");
} );

Try this:

$('.menu-toggle').click( function() {
    $("#primary-menu").toggleClass("someClass");
} );
.someClass{
    color: red;    
}   

 
   

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<nav id="primary-menu">

<a class="menu-toggle">Browse</a>

    <ul>

        <li><a href="#">Home</a></li>
        <li><a href="#">News</a></li>
        <li><a href="#">Rumors</a></li>
        <li><a href="#">Tutorials</a></li>
        <li><a href="#">Miscellaneous</a></li>

    </ul>

</nav> <!-- end #primary-menu -->

Upvotes: 11

JFK
JFK

Reputation: 41143

You could do

$(".menu-toggle").on("click", function(){
    $(this).parent("#primary-menu").toggleClass("active");
});

NOTE : .on() requires jQuery v1.7+

Upvotes: 0

Sid
Sid

Reputation: 189

I am not sure if I understand your question, but I think you are asking a similar question as this..Check out the below link, you can get the classname by Document.getElementsByClassName('Class name').

Remove class from elements in pure Javascript?

Upvotes: 0

shmuli
shmuli

Reputation: 5192

First make sure that you've loaded jQuery. Then try something like this:

 $( document ).ready(function() {
        $( "li" ).click(function() {
            $( "#primary-menu" ).toggleClass( "active" );
        });
    });   

Upvotes: 0

Related Questions