MSmS
MSmS

Reputation: 189

Is there a way to make every word different color in CSS?

So I wanted to make every word in the text different color, but I've only find code to make every letter in the text a different color. Is there any way to turn this to change color in every word instead every letter?

<script type="text/javascript">
       var message = "The quick brown fox.";
       var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, blue
       for (var i = 0; i < message.length; i++)
          document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>");
    </script>

Upvotes: 0

Views: 2631

Answers (4)

xdazz
xdazz

Reputation: 160833

Let's try some different way. The live demo.

var message = "The quick brown fox.",
    colors = ["#ff0000","#00ff00","#0000ff"],
    i = 0, len = colors.length;

message = message.replace(/\b(\w+)\b/g, function (match, word) {
    return '<span style="color: ' + colors[(i++ % len)] + ';">' + word + '</span>';
});
document.write(message);
​

Upvotes: 0

Chris
Chris

Reputation: 26878

var text = "Glee is very very awesome!";
text = text.split(" ");
var colors = ["red", "green", "rgb(0, 162, 232)"]; //you can use color names, as well as RGB notation
var n = colors.length; //no need to re-grab length each time
for(var i = 0; i < text.length; i ++) {
    document.write('<span style = "color: ' + colors[i % n] + '">' + text[i] + '</span>');
}

Little demo: little link.

Upvotes: 1

Bj&#246;rn
Bj&#246;rn

Reputation: 29381

var message = "The quick brown fox.",
    words   = message.split(/\s+/),
    colors  = ['#ff0000', '#00ff00', '#0000ff'];

for (var i = 0; i < words.length; i++) {
    document.write('<span style="color: ' + colors[(i % colors.length)] + ';">' + words[i] + '</span>');
}

Upvotes: 1

Mutation Person
Mutation Person

Reputation: 30498

Small change required.

Split the message into an array by space (" ")

   var message = "The quick brown fox.";
   var messageArr = message.split(" ");
   var colors = ["#ff0000","#00ff00","#0000ff"]; // red, green, blue
   for (var i = 0; i < messageArr .length; i++)
   {
      document.write("<span style='color:" + colors[(i % colors.length)] + ";'>" + messageArr[i] + " </span>");
   }

See it on this JSFiddle

Note: I've also changed your colors array definition to using the array literal notation [], which is a slightly better way of declaring an array.

Upvotes: 2

Related Questions