0

Is there a bit of CSS I can use that randomises the hover colour on links? For example, sometimes a user will hover over and it will be red, other times green, others blue. I know how to attach colour, I just wondered if it was possible to vary it/randomise it within a pool of colours, or whether it was limited to the one colour that you set.

Thank you!

  • Consider that this may be confusing to some users, who will believe there's some sort of meaning behind it. – ceejayoz Jan 02 '20 at 02:31
  • 1
    Does this answer your question? [How to show random color on hover in CSS?](https://stackoverflow.com/questions/31468794/how-to-show-random-color-on-hover-in-css) – Swetank Poddar Jan 02 '20 at 02:44

3 Answers3

1

You can achieve this by using javascript or jQuery reason is explained in this answer : explanation

Try to do something like this which might help you can resolve your query provided both javascript and jQuery example: example

Abhishek Pakhare
  • 476
  • 1
  • 4
  • 15
1

I don't know that there is any simple way to do this with css, but you can do this fairly easily with jquery.

<a href="#" class="random-color">Test link 1</a>
<a href="#" class="random-color">Test link 2</a>

<!-- source script for jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>

  // Colors array with whatever colors you want
  var colors = ['#ff8800','#ff00ff','#00ffcc'];

  // This applies a random color to the link when you hover it
  $('.random-color').mouseenter(function(){
    $(this).css('color', colors[ Math.floor( Math.random() * colors.length ) ]);
  });

  // This function will return the color of the link to default when the mouse leaves
  $('.random-color').mouseleave(function(){
    $(this).css('color', '#0000ee');
  });

</script>

You can see the working code here.

The links are assigned a class, in this case random-color, which is used to access it via the jquery selector $('.random-color'). the .mouseenter event triggers when your mouse is over the link, and then using $(this).css() you can apply the styles you need.

Using the colors[ Math.floor( Math.random() * colors.length ) ], you assign it a random element from the colors array. You can also add, subtract, or alter any of the colors in the array.

chris
  • 789
  • 4
  • 16
1

Use JavaScript to set the color onmouseenter and onmouseleave. Note that setting the color to an empty string gets rid of inline color styling to revert it back to the default CSS color.

<script src="https://randojs.com/1.0.0.js"></script>
<a onmouseenter="this.style.color = rando(['red', 'green', 'blue']).value;" onmouseleave="this.style.color='';" href="#">This is a link</a>

I used randojs.com to simplify the randomness, so make sure to add:

<script src="https://randojs.com/1.0.0.js"></script>

in the head tag of your html document if you want to use this code.

Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15