Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!