skip to Main Content
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>

<style>
#a, #b, #c {
  height: 100px;
  width: 100px;
  background-color:red;
  font-size: 100px;
  margin-bottom: 20px;
}

#a:active, #b:active, #c:active {
  background-color: blue;
}
</style>

When I click on #a, only #a changes color, when I click on #b, only #b changes color, and when I click on #c, only #c changes color.

What can I do so that when I click #a OR #b OR #c, all of them change color at the same time?

I do not know if the solution requires JS, but if it does, please answer using vanilla JS

2

Answers


  1. You would definitely need JavaScript (or jQuery) to accomplish this. Here is a simple way to do it with event listeners.

    The code below will apply a class to all elements when one of them is clicked and then remove it when the click is released.

    var elements = document.querySelectorAll('#a, #b, #c');
    
    for (var i = 0; i < elements.length; i++) {
      elements[i].addEventListener('mousedown', function() {
        for (var j = 0; j < elements.length; j++) {
          elements[j].classList.add('active');
        }
      });
    
      elements[i].addEventListener('mouseup', function() {
        for (var j = 0; j < elements.length; j++) {
          elements[j].classList.remove('active');
        }
      });
    
      elements[i].addEventListener('mouseleave', function() {
        for (var j = 0; j < elements.length; j++) {
          elements[j].classList.remove('active');
        }
      });
    }
    .active {
      background-color: blue !important;
    }
    
    #a, #b, #c {
      height: 100px;
      width: 100px;
      background-color:red;
      font-size: 100px;
      margin-bottom: 20px;
    }
    <div id="a">A</div>
    <div id="b">B</div>
    <div id="c">C</div>
    Login or Signup to reply.
  2. You need a simple script that applies to each element.

    And here’s how to do it…

    1. Add a class to all the elements.
    <div id="a" class="myCustomClass">A</div>
    <div id="b" class="myCustomClass">B</div>
    <div id="c" class="myCustomClass">C</div>
    
    1. create a .active class and design it accordingly.
    .active {
        background-color: blue !important;
    }
    
    1. Add this JavaScript.
    const myDivs = document.querySelectorAll(".myCustomClass");
            myDivs.forEach((e) => e.addEventListener("mousedown", () => {
                myDivs.forEach((div) => div.classList.add("active"));
            }));
            myDivs.forEach((e) => e.addEventListener("mouseup", () => {
                myDivs.forEach((div) => div.classList.remove("active"));
            }));
    

    The .forEach() method will loop through all the elements in the array and will perform the given action for all.

    I hope that helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search