How to have multiple link hover colors, different each rollover?

Viewed 43

I'm wondering the best and simplest way to make a link's hover state one of 5 different preselected colours, and every time you roll off and then back on, it has changed.

i.e. there's a black link to "contact" and if you hover the cursor over it becomes blue. Remove the cursor and then return it over the link and now it's red, etc.

I'm assuming js is the best way but I'm not very adept yet.

I'd also like to know how to do the above with divs (as I may want to do over an image or something similar) if it's a similar concept.

Thanks for any help!

1 Answers

This is doable in JavaScript, see the example below. The same concept would work regardless of element type.

const colors = ['blue', 'black', 'orange', 'green', 'purple', 'teal', 'pink'];

document.querySelectorAll('div')
  .forEach(div =>
  {
    div.addEventListener('mouseover', () => {
      div._originalColor = div.style.backgroundColor;
      div.style.backgroundColor = colors[Math.floor(Math.random()*colors.length)]
    }, true);
    
    div.addEventListener('mouseout', () => {
      div.style.backgroundColor = div._originalColor;
    }, true);
  });
<div style="width: 300px; height: 200px; background-color: red; margin: 5px; display: inline-block;"></div>

<div style="width: 300px; height: 200px; background-color: red; margin: 5px; display: inline-block;"></div>

Related