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