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

160
Visualizações
Is there a way to use a Javascript variable in CSS to customize colour, or an alternative way to achieve this?

I'm trying to make it so that when you over over certain elements on a webpage, they change to random colour of a predefined pallette.

I've written a basic scrip in JS that picks from an existing colour pallette.

const pal = ["93FFF2","F8A5FF","FFBA41","71FF5B","9D6CFF"]
const txtCol = Math.floor(Math.random() * pal.length);
console.log(txtCol, pal[txtCol]);

Then, ideally, I could use the "txtCol" value in my CSS, like so...

nav a:hover {
    color: (txtCol);
}

Obviously, that doesn't work. Is there any way I can achieve what I want this to do? Many thanks :)

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

0

You can do a combination of css variables and setting variables with javascript for every mouseenter event (when the hover starts):

nav a:hover {
  color: var(--hover-color);
}
const pal = ["93FFF2","F8A5FF","FFBA41","71FF5B","9D6CFF"]
// every time the user starts hovering that element
document.querySelector('nav a').addEventListener("mouseenter", (event) => {
  // pick the random color
  const txtCol = pal[Math.floor(Math.random() * pal.length)];
  // set the css variable
  event.target.style.setProperty('--hover-color', '#' + txtCol)
})
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