Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery add remove class onclick

i have any navigation menu !

   <div class="nav">
    <ul class="navigation">
    <li class="selected"><a href="#">HOME</a></li>
    <li><a href="#">PROFILE></a></li>
    <li><a href="#">CONTACTUS</a></li>
    <li><a href="#">ABOATUS</a></li>
    </ul>
    </div>

Now how to add selected class after click to any ( profile, Contactus, aboutus ) and remove selected home using Jquery.

Thanks

like image 524
Panaroma Avatar asked Aug 21 '11 11:08

Panaroma


2 Answers

On the assumption that you want to have only one element of class-name selected I suggest:

$('ul.navigation li a').click(
    function(e) {
        e.preventDefault(); // prevent the default action
        e.stopPropagation(); // stop the click from bubbling
        $(this).closest('ul').find('.selected').removeClass('selected');
        $(this).parent().addClass('selected');
    });

JS Fiddle demo.

like image 57
David Thomas Avatar answered Sep 19 '22 14:09

David Thomas


you can use toggleClass:

$("#myElement1").click(function(){
   $("#myElement2").toggleClass("myClass");
});
like image 22
Headshota Avatar answered Sep 19 '22 14:09

Headshota