How to Make Each Letter in Text a Different Random Color in JavaScript

Style each letter in a string with a random color/size on click of button

split and join the string, wrapping each letter with a span. Then you can assign different color to each of these spans.

function generateRandomColor() {
var colors = ["green", "blue", "red", "yellow", "cyan", "orange", "magenta"];
var randomColor = colors[Math.floor(Math.random() * colors.length)];
return randomColor;
};

function generateRandomFontSize() {
var sizes = ["12px", "14px", "16px", "18px", "20px"];
var randomSize = sizes[Math.floor(Math.random() * sizes.length)];
return randomSize;
};

function randomizeText() {
var elem = document.getElementById("header")
elem.style.color = generateRandomColor();
elem.style.fontSize = generateRandomFontSize();

elem.innerHTML = span_it(elem.innerText);
// now each letter
var spans = elem.querySelectorAll("span");
spans.forEach(span => span.style.color = generateRandomColor())

};

function span_it(str) {
return str.split("").map(letter => "<span>" + letter + "</span>").join("")
}
<h1 id="header" name="header" value="">JavaScript is fun!</h1>
<button type="button" onclick="randomizeText()">Randomize!</button>

how can I set random color for text area?

As per your requirement the color of each letter can't be displayed in textarea because you can't use html tags inside textarea but, can be displayed in div with contenteditable="true" property.

function myFunction(){
document.getElementById("myDiv").innerHTML = "";
let inputValue = document.getElementById("myInput").value
let splitValue = inputValue.split("");
splitValue.forEach((element)=>{
let text = element;
let result = text.fontcolor(getRandomColor());
document.getElementById("myDiv").innerHTML += result
})
}

function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
.divTextArea {
border: 1px solid black;
min-width: 175px;
min-height: 100px;
max-width: max-content;
max-height: max-content;
margin-top: 5px;
border-radius: 3px;
}
<input id="myInput" type="text" onchange="myFunction()">
<div class="divTextArea" contenteditable="true" id="myDiv"></div>

jQuery each letter in div element, random colour from array on hover

A string is not an element and you cannot add a CSS property to it. You can put your letters in span elements and then style them, try this:

$(document).ready(function() {

// COLOURS ARRAY
var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;

$('DIV#header').hover(function(){

$('span', this).each(function(index, character) {
idx = Math.floor(Math.random() * colours.length);
$(this).css("color", colours[idx]);
});

}, function() {
$('span',this).css("color","#ddd");
});

});

http://jsfiddle.net/BC5jt/

How can I give different color for each letter in a text field?

http://jsfiddle.net/DerekL/Y8ySy/

$("body").prop("contentEditable", true).blur(function(){
var chars = $(this).text().split("");
this.innerHTML = "";
$.each(chars, function(){
$("<span>").text(this).css({
color: "#"+(Math.random()*16777215|0).toString(16) //just some random color
}).appendTo("body");
});
});

You can actually set the event to keypress if the user is only going to enter with a normal keyboard. I used blur here because keypress/keyup will break the code if the user is entering text with IME.

As Billy Mathews mentioned, one might want to have an input that can be submitted by form. Here is a solution:

<input type="hidden" id="hiddenEle">

var chars = $(this).text().split("");
$("#hiddenEle").val($(this).text());
this.innerHTML = "";

Just for fun

Here is one that won't change color: http://jsfiddle.net/DerekL/A7gL2/

Random Colorful letters

If result is a text then you need to wrap each letter with span..
do like code below:

<div  id="list" rows="10"></div>
<script>
$(function() {
setTime();
function setTime() {
$.ajax({
url : "../abc.php",
dataType: "text",
success : function (result) {
$("#list").html(result);
$("#list")
.contents()
.filter(function(){
return this.nodeType !== 1;
})
.wrap( "<b class='colorful_text'></b>" );
$.each($(".colorful_text"), function(o, v){

var textEle = $(this).text()
console.log("textEle", textEle)
$(this).html("")
for(var n=0; n<textEle.length; n++) {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
var color = '#' + randomColor
var ele = document.createElement("span")
ele.style.color = color
ele.innerText = textEle[n]

$(this).append(ele)

}

})
}
});
var date = new Date().getTime();
setTimeout(setTime, 3000);
$("#list").html();

//Here should call a function to color all the words of the div
}

});
</script>

How to style every word with different color using javascript?

Unfortunately input tag words can't have different colors, since text and input are not separate elements, but for other elements you can wrap each word into span and add style to them, that is how rich content editors are working.

Assume you have <p id="paragraph">Here are few words</p> and you want to add different colors to each word.

You can split innerText of #paragraph and create span for each word and insert result as innerHTML of #paragraph.

Here is example

var paragrapgh = document.getElementById("paragraph");var words = paragrapgh.innerText.split(" "); // here I am spliting words by space i.e tokenizing itvar colors = ["red","green","blue","pink", "gold", "yellow", "blueviolet"];var spans = [];
for(var x = 0; x < words.length; x++){ var color = colors[Math.floor(Math.random()*colors.length)] // geting random color from array; var span = "<span style='background-color: " + color + ";'>" + words[x] + "</span>" spans.push(span);}
// setting colored spans as paragraph HTMLparagrapgh.innerHTML = spans.join(" ");
<p id="paragraph">Here are few words</p>


Related Topics



Leave a reply



Submit