TransWikia.com

CSS active styling is not remaining

Stack Overflow Asked by unkown53 on December 9, 2021

Im trying to keep a clicked button active as long as it is still clicked. I have tried a lot of things but this doesnt seem to work. The colored effect doesnt last more than 1 second and it’s not depending from the click.
Here is my code :

// Add active class to the current button

var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    if (current.length > 0) {
      current[0].className = current[0].className.replace(" active", "");
    }
    this.className += " active";
  });
}
.active {
  background-color: #545454;
}
<div id="myDIV">
  <table class="secondTable">
    <tr>
      <th><button class="btn" style="margin-left: -6px;">button1</button></th>
      <th></th>
      <th></th>
    </tr>
    <tr>
      <th><button class="btn" style="margin-left: -6px;">button2</button></th>
      <th></th>
      <th></th>
    </tr>
  </table>
</div>

I have tried every possible thing but im not able to figure out what the problem is. The styling should just involve color changing.
NB: my css looks like this .active { background-color: #545454; }
Thanks a lot!

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP