Button: Active using JavaScript and CSS

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.


You could use classList.toggle() in conjunction to a .active class.

So your code would look something like this:

<!DOCTYPE HTML>
<html>
    <head>
        <style>
        .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;
        }
        </style>
    </head>
    <body>
        <button class="btn">Button</button>
        <button class="btn">Button</button>
        <button class="btn">Button</button>
        <button class="btn">Button</button>
    </body>
    <script>
        function toggleActiveState() {
            this.classList.toggle('active');
        }
        var btns = document.querySelectorAll('.btn');
        [].forEach.call(btns, function(btn) {
          btn.addEventListener('click', toggleActiveState, false);
        });
    </script>
</html>

This aproach would work for a infinite number of buttons.


See https://developer.mozilla.org/en-US/docs/Web/CSS/:active What's happening now is that it's working just fine :-) but what you're asking it to do and what you want it to do are not the same thing.

I think you need to fix your css and define active as a class rather than a pseudo-class (untested, but here goes):

.active {
   background: #cecece;
}