Trying to make a simple button to be in an active, different style when it is clicked on. I am using HTML to lay out the button, CSS for styling, and hoping to use a bit of JavaScript to do so.
After looking around SO and finding there are many different ways such as using Checkbox to make a button by pure CSS, or jQuery, or JavaScript, I feel that JavaScript is the most close way that I am looking at.
HTML
<button type="button" class="btn" id="btn1">Details</button>
CSS
.btn {
background: #3498db;
border-radius: 0px;
font-family: Arial;
color: #ffffff;
font-size: 12px;
padding: 2px 2px 2px 2px;
text-decoration: none;
height: 30px;
width: 70px;
margin-top: 5px;
margin-bottom: 5px;
display: block;
}
.btn:active {
background: #cecece;
text-decoration: none;
}
JavaScript
$('.btn').click(function(){
if($(this).hasClass('active')){
$(this).removeClass('active')
} else {
$(this).addClass('active')
}
});
Here is a jsfiddle link: http://jsfiddle.net/w5h6rffo/
Additional Note
Feature goal is to have multiple buttons with the same class but each button calling to a different functions. I have the calling of the functions working, just not the button staying at an active state when it is first pressed, then at an inactive state when it is pressed again
You're close to doing it right, the mechanism you built using a check to see if your element has the active
class is nice but jQuery has a toggleClass()
function which allows you to just write the following:
$('.btn').click(function() {
$(this).toggleClass('active');
});
Then in your CSS, instead of styling the pseudo :active
you'll use a classname instead like this:
.btn.active {
background: #cecece;
text-decoration: none;
}
You'll also want to remove the :):active
selector from your CSS altogether since you won't be needing it anymore
As dfsq pointed out there is a certain value in retaining the :active
pseudo selector:
I just think that active state (:active) for the control elements is important. For example, without it button will look the same if it is pressed but not clicked (mouseout before mouseup). UX is slightly better with :active.
But maybe I'm too picky
For this reason you might want to modify the selector to be:
.btn.active, .btn:active {
background: #cecece;
text-decoration: none;
}
As this will affect both the '.active' and the ':active' state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With