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

352
Visualizações
Automatically generating and display color code after pressing button

I have a button "White color" and I am curious how can I make the text under the button "#White" automatically generate after clicking on it and not be hardcoded as in the example I have below. For example showing as "#000000" after pushing the button.

const buttonColor = document.querySelector("[data-buttColor]");
const pEl = document.querySelector("[data-colorCode]");
const background = document.querySelector("[data-background]");

const buttonColorWhite = document.querySelector("[data-buttColorWhite]");
const buttonColorBlack = document.querySelector("[data-buttColorBlack]");

buttonColor.addEventListener("click", () => {
  let color = "#";
  color += Math.random().toString(16).slice(2, 8);
  background.style.backgroundColor = color;
  pEl.innerText = color;
  console.log(color)
})

buttonColorWhite.addEventListener("click", () => {
  let colorWhite = background.style.backgroundColor = "white";
  let color = "#white";
  pEl.innerText = color;
  console.log(color)

})

buttonColorBlack.addEventListener("click", () => {
  let colorWhite = background.style.backgroundColor = "black";
  let color = "#black";
  pEl.innerText = color;
  console.log(color)
})
<div class="text-center text-white animate__animated animate__flipInX">
  <button data-buttColor class="btn btn-primary btn-lg mt-3">Random color</button>
  <button data-buttColorWhite class="btn btn-primary btn-lg mt-3">White color</button>
  <button data-buttColorBlack class="btn btn-primary btn-lg mt-3">Black color</button>
  <p data-colorCode>The color is</p>
  <p data-background>&nbsp;</p>
</div>

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

0

This answer still have hard coded hexadecimals, but in a different way that is easier to handle.

First of all, I changed your camelCase attributes to be kebab-cased instead, ex. data-colorCode --> data-color-code.

I also assigned (hard coded) values to data-butt-color for the white and black buttons.

The last thing I did were to querySelect all buttons, and then loop through the nodes to assign a click listener to each one of them, where I read the assigned data-butt-color or randomizing if there is no value. I also took the liberty of refactoring the code, in an attempt to make it more readable.

const pEl = document.querySelector("[data-color-code]");
const background = document.querySelector("[data-background]");
const buttons = document.querySelectorAll('button');

buttons.forEach((button) => {
  button.addEventListener('click', () => {
    let color = getColor(button.dataset.buttColor);
    displayColor(color);
  });
});

function getColor(color) {
  if (!color) {
    color = Math.random().toString(16).slice(2, 8);
  }

  return '#' + color;
}

function displayColor(color) {
  background.style.backgroundColor = color;
  pEl.innerText = `The color is: ${color}`;
}
<div class="text-center text-white animate__animated animate__flipInX">
  <button data-butt-color       class="btn btn-primary btn-lg mt-3">Random color</button>
  <button data-butt-color="fff" class="btn btn-primary btn-lg mt-3">White color</button>
  <button data-butt-color="000" class="btn btn-primary btn-lg mt-3">Black color</button>
  <p data-color-code>The color is:</p>
  <p data-background>&nbsp;</p>
</div>

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