Hi I want to make kind of type checker. so when you put some text to input box, that text appear to the textarea. I want to set random text color for textarea.. I used this code :
let letters = document.querySelector('#txt').innerHTML.split('');
let quote = document.querySelector('#author').innerHTML.split('');
// Converts integer to hex
const colToHex = (c) => {
// Hack so colors are bright enough
let color = (c < 75) ? c + 75 : c
let hex = color.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
// uses colToHex to concatenate
// a full 6 digit hex code
const rgbToHex = (r,g,b) => {
return "#" + colToHex(r) + colToHex(g) + colToHex(b);
}
// Returns three random 0-255 integers
const getRandomColor = () => {
return rgbToHex(
Math.floor(Math.random() * 255),
Math.floor(Math.random() * 255),
Math.floor(Math.random() * 255));
}
// This is the prototype function
// that changes the color of each
// letter by wrapping it in a span
// element.
Array.prototype.randomColor = function() {
let html = '';
this.map( (letter) => {
let color = getRandomColor();
html +=
"<span style=\"color:" + color + "\">"
+ letter +
"</span>";
})
return html;
};
// Set the text
document.querySelector('#txt').innerHTML = letters.randomColor();
document.querySelector('#author').innerHTML = quote.randomColor();
but it is not working... Is there any solutions..? regards.
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>