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 :)
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)
})