user1669296
user1669296

Reputation: 445

AddClass/RemoveClass jQuery 2.x

I have a set of hyperlinks that act as buttons that are direct children of a div. When the user clicks one of the links/buttons, it sets the class to 'active' and when they click another link/button it removes the active class, sets that button to inactive and then sets active on the link/button the user actually clicked.

The problem is I also need to be able to de-select a link/button if the user clicks the same button, basically like a toggle. I can't seem to integrate that into my code. Can someone use what I have below and add to it a way to toggle the class if the user clicks the same button/link instead of a different one?

$('#divResponses a').on('click', function(){

 $(this).closest('div').find('a').removeClass('active').addClass('notActive') ;
 $(this).removeClass('notActive').addClass('active');

}

--html--
<div id="divResponses">
 <a href="" class="btn notActive">Button1</a>
 <a href="" class="btn notActive">Button2</a>
 <a href="" class="btn notActive">Button3</a>
 <a href="" class="btn notActive">Button4</a>
</div>

Upvotes: 0

Views: 78

Answers (3)

Scott
Scott

Reputation: 21882

I would simplify the HTML:

<div id="divResponses">
 <a href="#" class="btn active">Button1</a>
 <a href="#" class="btn">Button2</a>
 <a href="#" class="btn ">Button3</a>
 <a href="#" class="btn ">Button4</a>
</div>

Assuming the default state of the link is notActive so a special class for that may not really be necessary. just style the .btn class accordingly. If you want a link to be active by default, add the .active class to it.

Then toggle the active class....

$('#divResponses a').on('click', function(){
    $('#divResponses a').removeClass('active'); //Removes any active class on other links
   $(this).toggleClass('active'); //toggles active on the click element
});

If you do not want to deactivate previously clicked links then:

$('#divResponses a').on('click', function(){
       $(this).toggleClass('active'); //toggles active on the click element
    });

jsFiddle demo

If you want to keep your notActive class : jsFiddle demo for that

Upvotes: 0

Wim Mertens
Wim Mertens

Reputation: 1790

I would use toggleClass and use siblings to target the rest of the links:

$(this).toggleClass('active').siblings('a').removeClass('active');

Upvotes: 1

Skua
Skua

Reputation: 19

Surely you need to define an id for each button? Like so:

<a href="" id="1" class="btn notActive">Button1</a>
<a href="" id="2" class="btn notActive">Button2</a>
<a href="" id="3" class="btn notActive">Button3</a>   

And then proceed to check if the same button is clicked twice using that id?

Upvotes: 0

Related Questions