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');
});
});
You should use $(this)
to add active
class to the clicked button
$(document).ready(function(){
$('.btn').click(function() {
$(this).addClass('active');// use this here
});
});
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.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加