No need for jQuery, just apply CSS styling to a class and use Vanilla JavaScript to add or remove that class.
let body = document.querySelector('body'),
box = document.querySelectorAll('.box');
body.addEventListener('click', function(e) {
let cl = e.target.classList;
if (cl.contains('box'))
cl.toggle('active');
});
.box {
background: blue;
display: inline-block;
margin: 5px;
height: 2.5rem;
width: 2.5rem;
}
.active {
background: red;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
- Adds a click event listener to the parent element (in this case, the body) instead of creating multiple listeners for each box element, improving performance
- By checking the event target's class during the click event, we can determine whether it was a box that was clicked. This prevents adding the active class to unintended elements
To make the code even shorter, you can replace the if block with
cl.contains('box') && cl.toggle('active');
, which toggles the active class if the element has a box class.