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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With