In this article, we will find how to set a different color for each letter in a text field using jQuery?
Approach:
To do this we will have to change the color of text whenever the user enters a letter using the keyboard. For this, we will use onkeydown event that triggers whenever the user presses a key on the keyboard.
Syntax:
object.onkeydown = function(){Script}
Example: Let us look at an example to find how to set a different color for each letter in a text field using jQuery onkeydown event.
HTML
<!DOCTYPE html>
< html >
< head >
< script src =
</ script >
</ head >
< style >
div {
border: 1px solid black;
margin-top: 40px;
margin-left: 250px;
margin-right: 250px;
}
</ style >
< body style = "text-align: center" >
< h2 style = "color: green" >GeeksforGeeks</ h2 >
< div id = "input" ></ div >
< script >
function setRange(text) {
var r, s;
if (document.createRange) {
r = document.createRange();
r.selectNodeContents(text);
r.collapse(false);
s = window.getSelection();
s.removeAllRanges();
s.addRange(r);
}
}
// Selecting input tag and applying css to each word
$("#input")
.prop("contentEditable", true)
.on("input", function () {
$(this)
.contents()
.each(function () {
var content = this;
$.each($(this).text().split(""), function () {
// Generating random color each time
var color = "#" + ((Math.random() * 16777215) | 0).toString(16);
$("< span >")
.text(this)
.css({ color: color })
.insertBefore(content);
});
$(this).remove();
});
// Function to set the end of the text content
setRange($("#input"));
});
</ script >
</ body >
</ html >
|
Output:

Change color of text using keydown event
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
18 May, 2021
Like Article
Save Article