How To Change Colors Of Individual Characters In A Header
Solution 1:
Well, after calling the function once x.innerHTML
will not only contain the text, but also the HTML for the font
elements. If you want to get the inner text only, you can use textContent
or innerText
(depending on the browser):
var x = document.getElementById("demo");
var text = x.textContent || x.innerText;
var newText="";
for(var a=0; a < text.length; a++) {
var letter = text.charAt(a);
// ...
}
If you don't care about IE8 or IE7, you can do this more elegantly with:
var new_text = Array.prototype.map.call(x.textContent || x.innerText, function(letter) {
return letter.fontcolor(getColor());
}).join('');
But you really shouldn't use the font element anymore, it's deprecated since ages.
Solution 2:
Warning: fontcolor
is not standard and <font>
elements are deprecated!
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
You can use .textContent
:
functionmyFunction()
{
var x = document.getElementById("demo"),
txt = x.textContent,
newText = "";
for(var i=0, l=txt.length; i<l; i++)
{
newText += txt.charAt(i).fontcolor(getColor());
}
x.innerHTML = newText;
}
Solution 3:
You could use
functionmyFunction()
{
var x = document.getElementById("demo"),
txt = x.innerHTML;
(myFunction = function() {
var newText = "";
for(var i=0, l=txt.length; i<l; i++)
{
newText += '<span style="color:#'+getColor()+'">'+txt.charAt(i)+'</span>';
}
x.innerHTML = newText;
})();
}
It works on old browsers because it doesn't use .textContent
, and doesn't use the non-standard fontcolor
Solution 4:
Well, you could before you replace the text, you move the text in the title attribute, and then use the attribute for the original text and then you will always have the original text. For example:
<h1>Flip That</h1>
Then you have your script before it does the random colors set the title if it hasn't been set before like below:
<h1title="Flip That">Flip That</h1>
Then you always use the title instead for the original string:
<h1title="Flip That"><fontcolor="#0a0a0a">F</font><fontcolor="#0b0b0b">l</font><fontcolor="#0c0c0c">i</font><fontcolor="#0d0d0d">p</font><fontcolor="#0e0e0e"></font><fontcolor="#0a0a0a">T</font><fontcolor="#0b0b0b">h</font><fontcolor="#0b0b0b">a</font><fontcolor="#0b0b0b">t</font></h1>
Post a Comment for "How To Change Colors Of Individual Characters In A Header"