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

152
Visualizações
How to swap <div> elements by using "mouseover" event?
let wrapperSt = document.querySelector(".wrapper");

for(i=0; i<100; i++){
let divGroup = document.createElement('div');
wrapperSt.append(divGroup);
divGroup.className= 'pixel';
divGroup.textContent= '';
}

I've created the div element called "pixel" by using loop because, i need couple hundreds of them. (I'll use them as a little boxes that could change color)

But, i want these boxes ("pixel" div) to turn brown and sustain (style.backgroundColor ="brown";)

So, i created another div that will replace the previous div ("pixel").

let selectPx = document.getElementsByClassName("pixel");

selectPx.addEventListener("mouseover", function(){

let pxChange = createElement("div");
//This is where i got stuck!

})

I could not finish my code, i found it a bit complicated even if it is probably something very simple.

Any suggestions or piece of information would be very helpful. Thank you.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Not sure exactly what you are trying to do... I think you are trying to change the color of the div that your mouse is over? If so, you have a couple of issues with your code. Instead of adding the event listener to the list of divs, you need to add it to each one individually. Also, you should only need to change the background color of each element instead of creating a new one each time.

let selectPx = document.querySelectorAll(".pixel");

selectPx.forEach(pixel => {
  pixel.addEventListener("mouseover", () => {
    pixel.style.backgroundColor = "brown";
  });
});
about 4 years ago · Juan Pablo Isaza Relatório

0

I'm not sure why you have to create a new div inside the first one. In your code, when you trigger the mouseover event you can get the div under the mouse and apply the style to it:

let selectPx = document.getElementsByClassName("pixel");

selectPx.addEventListener("mouseover", function(evt){

    let divUnderMouse = evt.target;
    divUnderMouse.style.backgroundColor ="brown";

})

I haven't tried it but it should work

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