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

341
Visualizações
JavaScript, for each hover over change the text color

I have 4 div (colored box) and each div represent a different color. When a user hovers over one of the colored boxes the text to display ("Hello world") should change to the color that is being hovered over. I wrote the code for each color, but it seems worng because I'm copying the code many times for each color. How can I make this code shorter and more efficient?

document.addEventListener('DOMContentLoaded', function() {

  const textToChange = document.getElementById('change_heading');

  const brownColor = document.querySelector('.brown');
  const greenColor = document.querySelector('.green');
  const blueColor = document.querySelector('.blue');

  brownColor.addEventListener('mouseover', function() {
    textToChange.classList.add('brown');
  });

  brownColor.addEventListener('mouseout', function() {
    textToChange.classList.remove('brown');
  });

  greenColor.addEventListener('mouseover', function() {
    textToChange.classList.add('green');
  });

  greenColor.addEventListener('mouseout', function() {
    textToChange.classList.remove('green');
  });

  blueColor.addEventListener('mouseover', function() {
    textToChange.classList.add('blue');
  });

  blueColor.addEventListener('mouseout', function() {
    textToChange.classList.remove('blue');
  });

});
div {
  width: 50px;
  height: 50px;
  display: inline-block;
}

.brown {
  background-color: brown;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.yellow {
  background-color: yellow;
}
<h1 id="change_heading">Hello World</h1>
SELECTED COLOR <span class="selected">None!</span>
<section>
  <div class="brown"></div>
  <div class="green"></div>
  <div class="blue"></div>
  <div class="yellow"></div>
</section>

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

0

You could shorten your code this way:

document.addEventListener('DOMContentLoaded', function() {
  const textToChange = document.getElementById('change_heading');
  const corloredDivs = document.querySelectorAll('section div');
  
  corloredDivs.forEach(d=>{
      d.addEventListener('mouseover', function() {
          textToChange.classList.add(d.classList[0]);
      });
      d.addEventListener('mouseout', function() {
        textToChange.classList.remove(d.classList[0]);
      });
   });

});
div {
  width: 50px;
  height: 50px;
  display: inline-block;
}

.brown {
  background-color: brown;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.yellow {
  background-color: yellow;
}
<h1 id="change_heading">Hello World</h1>
SELECTED COLOR <span class="selected">None!</span>
<section>
  <div class="brown"></div>
  <div class="green"></div>
  <div class="blue"></div>
  <div class="yellow"></div>
</section>

about 4 years ago · Juan Pablo Isaza Relatório

0

The above code is absolutely better. This is how I have shortened it.

document.addEventListener('DOMContentLoaded', function () {

const textToChange=document.getElementById('change_heading');

  let allDivs = document.getElementsByClassName('a');

for (const div in allDivs) {
  let currentClassName = allDivs[div].className.split(" ")[1];
  allDivs[div].addEventListener('mouseover', function(){
    textToChange.classList.add(currentClassName);
});
    allDivs[div].addEventListener('mouseout', function(){
    textToChange.classList.remove(currentClassName);
});
}
});
 div {
        width: 50px;
        height: 50px;
        display: inline-block;
    }
    .brown {
        background-color: brown;
    }

    .green {
        background-color: green;
    }

    .blue {
        background-color: blue;
    }
    .yellow {
        background-color: yellow;
    }
<body>
<h1 id="change_heading">Hello World</h1>
SELECTED COLOR <span class="selected">None!</span>
<section>
    <div class="a brown"></div>
    <div class="a green"></div>
    <div class="a blue"></div>
    <div class="a yellow"></div>
</section>
<script src="script.js"></script>

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