Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight elements in a css grid layout using javascript

I got a css grid with 25 div elements. Each element should switch between being highlighted and normal when clicked on.

Since each element can be individually turned on and off, I made a box_state variable for each and set it to false as initial value so it can be set to true once its turned on.

To highlight each element I got this block of code:

    document.querySelector("#n_1").onclick = function() {
    if (box_1_state === false) {
        document.querySelector("#n_1").style.filter = "brightness(150%)";
        box_1_state = true;
    } else {
        document.querySelector("#n_1").style.filter = "brightness(100%)";
        box_1_state = false;
    }

} 

n_1 is the name of the div in the html file and box_1_state is the variable mentioned above.

So to make this work I have to make the code block above 25 times which kind of seems it could be done easier. Any suggestions?

like image 304
user3801167 Avatar asked Jan 20 '26 17:01

user3801167


1 Answers

  • All you need is Element.classList.toggle() and a specific CSS class, i.e: "is-active"
  • PS: filter brightness expects a maximal value of 100%

const ELS_box = document.querySelectorAll(".box");
ELS_box.forEach(EL => EL.addEventListener("click", function() {
  this.classList.toggle("is-active");
}))
.boxes {
  display: grid;
  grid-template-columns: repeat(5, 30px);
  grid-template-rows: repeat(5, 30px);
  grid-auto-flow: column;
}

.box {
  margin: 5px;
  background: red;
}

.box.is-active {
  filter: brightness(50%);
}
<div class="boxes">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
like image 60
Roko C. Buljan Avatar answered Jan 23 '26 06:01

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!