Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random coloured words in a H1

Is it possible to have each word in a H1 a random colour and that if you refresh the page these will then be randomised again?

I have 5 set colours I want to use. How would I code this ?

like image 907
Gezzamondo Avatar asked Dec 13 '25 10:12

Gezzamondo


1 Answers

Yes, that's possible :

var colors = ['red', 'yellow', 'blue', 'green', 'black'];
$('h1').each(function(){
    $(this).html($(this).text().split(' ').map(function(v){
        return '<span style="color:'+colors[Math.floor(Math.random()*colors.length)]+'">'+v+'</span>';
    }).join(' '));
});​​​​​​

The main idea is to split the content of each h1 into words and replace the words by embedding them in <span> as you can't style a word but only an element.

Demonstration

like image 68
Denys Séguret Avatar answered Dec 14 '25 22:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!