Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
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?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you don't want to use a class, you can store its state in a custom attribute:

const divs = document.querySelectorAll('div');
divs.forEach(e => {
  e.addEventListener('click', function() {
    if (e.dataset.brightened != "true") {
      e.style.filter = "brightness(150%)";
      e.dataset.brightened = "true";
    } else {
      e.style.filter = "brightness(100%)";
      e.dataset.brightened = "false";
    }
  })
})
div {
  height: 100px;
  width: 100px;
  border: 1px solid;
  background-color: #ededed;
}
<div></div>
<div></div>
<div></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

A method to automate this is by surrounding your code with a loop, and then use the loop's iterator/index to use as the querySelector

let numberOfDivElements = 25;
let box_states = [];

for (let iterator = 0; iterator < numberOfDivElements; iterator++) {
    // Initialize an array to store your "box states", whether true or false
    box_states[iterator] = false;
}

for (let iterator = 0; iterator < numberOfDivElements; iterator++) {
    let boxSelector = "#n_" + iterator;

    // Your example code
    document.querySelector(boxSelector).onclick = function() {
        if (box_states[iterator] === false) {
            document.querySelector(boxSelector).style.filter = "brightness(150%)";
            box_states[iterator] = true;
        } else {
            document.querySelector(boxSelector).style.filter = "brightness(100%)";
            box_states[iterator] = false;
        }
    }
    // End of your example code

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda