jquery add remove class onclick
Asked Answered
F

3

11

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

Footprint answered 21/8, 2011 at 11:38 Comment(0)
M
14

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.

Milena answered 21/8, 2011 at 12:4 Comment(1)
Sorry, can you explain what you mean by e.stopPropagation() bubbling up the dom tree? Is it in case the surrounding wrappers are attached to click events?Wulfenite
O
8

you can use toggleClass:

$("#myElement1").click(function(){
   $("#myElement2").toggleClass("myClass");
});
Oralee answered 21/8, 2011 at 11:40 Comment(0)
K
4
$("a").click(function()
{
  $("a").parent().removeClass("selected");

  $(this).parent().addClass("selected");
});

Live Demo

Kirstenkirsteni answered 21/8, 2011 at 11:41 Comment(1)
Thanks i tested this, This Worked For Which ID , Class Or All a linkFootprint

© 2022 - 2024 — McMap. All rights reserved.