Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery toggle multiple buttons

Tags:

jquery

toggle

I have multiple buttons, that get their active css style with a jquery toggle script. But I want to have only one button at a time active. But also, when I re-click an active button, it has to become unactive.

$(document).ready(function(){
    $('.button').click(function() {       
        $(this).toggleClass('buttonactive');
    });
});

Basicly I need to add a line saying:

$(all .button except this).removeClass('buttonactive');

I don't know how. Can someone help me? Here's a JSFIDDLE with the problem: http://jsfiddle.net/nV5Tu/3/

like image 931
ThomasCS Avatar asked Jan 23 '13 14:01

ThomasCS


1 Answers

You can do it like this using .toggleClass() to toggle current element.. then using .not() to filter out current element from having class removed

$('.button').click(function() {  
    $('.button').not(this).removeClass('buttonactive'); // remove buttonactive from the others
    $(this).toggleClass('buttonactive'); // toggle current clicked element
});

FIDDLE

like image 95
wirey00 Avatar answered Nov 15 '22 07:11

wirey00