Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda