1

I want to build a page where a user can select multiple items by clicking on a button. I already used focus and active classes to make the buttons change appearance but with my current code I can only activate one single button. I'm looking for code that enables a user to activate multiple buttons.

HTML

<button class="btn btn-1">
    button 1
</button>

<button class="btn btn-1">
    button 2
</button>

<button class="btn btn-1">
    button 3
</button>

<button class="btn btn-1">
    button 4
</button>

CSS

.btn:hover {
  background-color: rgba(52, 152, 219,0.6);
}

.btn:focus {
  background-color: rgba(52, 152, 219,0.6);
}

.btn:active, .btn:visited {
  background-color: rgba(52, 152, 219,0.6);
}

.active {
  background-color: rgba(52, 152, 219,0.6); 
}

This is the jQuery code I have been using to try and add a permanent active class to those buttons that have been clicked. This is not working yet.

$(document).ready(function(){ 
    $('.btn').click(function() { 
        $('.btn').addClass('active');
    });
});

2 Answers 2

6

You should use $(this) to add active class to the clicked button

$(document).ready(function(){ 
    $('.btn').click(function() { 
       $(this).addClass('active');// use this here
    });
});

Demo

EDIT - as suggested by @Regent, you can use toggleClass to active and deactive on button click, use below code

$(document).ready(function(){ 
     $('.btn').click(function() { 
        $(this).toggleClass('active');
    });
 });

Demo for toggleClass Note - here I have commented .btn:focus css class because on second click button looks active as it is focused.

1
  • 1
    And just to mention: if you want to be able to deactivate button clicking again on it, you can use toggleClass instead of addClass.
    – Regent
    Sep 12, 2014 at 12:47
0

This should do it.

$(document).ready(function(){ 
$('.btn').click(function() { 
    $('.btn').toggleClass('active');
});
});

I think if you use "this" the action only takes effect in the button you are clicking itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.