Home > Enterprise >  How to have multiple buttons in focus? HTML/CSS/JS
How to have multiple buttons in focus? HTML/CSS/JS

Time:11-15

I have been trying to come up with a way to keep multiple buttons on or have them toggled in some way or another, im not really experienced with JavaScript but I saw that you could add a class on click but that wont work since I already have a class set. Maybe adding an ID to the element might work?

I need this snippet to be on every button that is toggled on in a specific <section>

button:focus {
    background-color: #2ce98e;
    color: #131621;
    cursor: pointer;
}

Thanks in advance :)

CodePudding user response:

Hope this is what you looking for

Toggle the presence of a class on button click

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Toggle buttons</title>
    <style>
      .button-focus {
        background-color: #2ce98e;
        color: #131621;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <button class="btn btn-one">Button one</button>
    <button class="btn btn-two">Button two</button>
  </body>
  <script>
    //   get all the elements on the basis of their class name
    let btn = document.getElementsByClassName("btn");

    for (var i = 0; i < btn.length; i  ) {
      (function (index) {
        btn[index].addEventListener("click", function () {
          console.log("Clicked Button: "   index);

          let isPresent = false;

          //   Check if the class is present or not
          this.classList.forEach(function (e, i) {
            if (e == "button-focus") {
              isPresent = true;
            } else {
              isPresent = false;
            }
          });

          //   toggle the presence of class on the basis of the isPresent variable
          if (isPresent) {
            this.classList.remove("button-focus");
          } else {
            this.classList.add("button-focus");
          }
        });
      })(i);
    }
  </script>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related