Button: Active using JavaScript and CSS

47,714

Solution 1

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.

Solution 2

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.

Solution 3

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;
}

Solution 4

This is pure HTML, CSS and JS Approach! I hope it will be helpful!!

const room  = document.querySelector('.chat-rooms');
const btns = document.querySelectorAll('.btn'); 

room.addEventListener('click', e => {

 btns.forEach(btn => {

    if(btn.getAttribute('id') === e.target.getAttribute('id'))
      btn.classList.add('active');
    else
      btn.classList.remove('active');
    });
});
.active,.btn:hover{ background-color:rgb(123, 255, 0); }
    <div class="chat-rooms">
      <button class="btn" id="general">#general</button>
      <button class="btn" id="gaming">#gaming</button>
      <button class="btn" id="music">#music</button>
      <button class="btn" id="coding">#coding</button>
    </div>
[You can refer my code pen snippet to test!] 
> > https://codepen.io/blueKode/pen/abdZmYJ

Solution 5

You can use jQuery's toggleClass( className ) function.

http://api.jquery.com/toggleclass/

<script>
    $("button.btn").click(function() {
        $(this).toggleClass("active");
    });
</script>

<style>
    .active{
      // your active style
     }
<style>
Share:
47,714
axchink
Author by

axchink

Updated on November 24, 2020

Comments

  • axchink
    axchink over 3 years

    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