Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I apply the :active pseudoclass to multiple elements at the same time?

<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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading