I\'m trying to alternate the colors of every letter in a specific div on my webpage using javascript.
I found this script on a forum that alternates the color of the wor
Here is one way to do this, just replace your JavaScript code with the following (and remove the form from your HTML since you just want this to happen on page load):
var HTML = '';
function alternate(colorpair) {
var el = document.getElementById('alternator');
if (!HTML) HTML = el.innerHTML;
var text = HTML.match(/\S\s*(?=\S)/g), output = '';
for (var w=0; w' + text[w] + '';
}
console.log(output);
el.innerHTML = output;
}
alternate(['green', 'purple']);
Note that with this method you will also skip spaces so the coloring looks a little better. Here is what the end result looks like:
Example: http://jsfiddle.net/pzeCQ/