Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda