Open In App

How to set different color for each letter in a text field using jQuery ?

Last Updated : 18 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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



Similar Reads

How to process each letter of text using JavaScript ?
Given a string and the task is to process it character by character. JavaScript String toUpperCase() Method: This method converts a string to uppercase letters. Syntax: string.toUpperCase()Parameters: This method accepts single parameter str which is required. It specifies the string to be searched.Return Value: It returns a string denoting the val
2 min read
How to find inputs with an attribute name starting with specific letter or text using jQuery?
In this article, we will learn to find input with an attribute name starting with a specific letter or text. This task is implemented using attributeStartWith selector. attributeStartWith selector: This selector selects elements that have the specified attribute with a value beginning exactly with a given string. It has two arguments i.e attribute
1 min read
How to place cursor position at end of text in text input field using JavaScript ?
In this article, we are going to learn about how to place the cursor at the end of the text in a text input element using JavaScript.  At first, we are going to create a text input box where some value will be given and a button to place the cursor at the end. We can place the cursor at the end of the text in a text input element by using different
2 min read
JQuery | Set focus on a form input text field on page load
The task is to set the focus on form input text field using jQuery. To do so, Here are a few of the most used techniques discussed. First focus() method needs to be discussed. jQuery focus() MethodThe focus event happens when an element gets focus (Either selected by a mouse click or by "tab-navigating" to it). This method triggers the focus event
2 min read
JQuery Set the value of an input text field
In this article, we will learn about the different methods of setting the value of the input field on any web page by clicking on a button using jQuery. There are some in-built methods available in jQuery that we can use for this purpose as listed below: Table of Content jQuery val() methodjQuery prop() methodjQuery attr() methodLet us now discuss
3 min read
How to prevent a text field losing focus using jQuery ?
In this article, we will learn how to prevent a textfield or an input from losing focus using jQuery. This can be used in situations where user validation is required. There are two approaches that can be taken: Approach 1: We will be using the jQuery bind(), val(), preventDefault() and focus() methods. The bind() method is used to attach a "focuso
3 min read
How to Allow Only Special Characters and Spaces in Text Field Using jQuery ?
We are going to create an input box that only contains the special characters and the space as the input. It will show an error if any other character is entered. We will use regular expressions that consist of only special symbols and spaces with different events in jQuery. Table of Content Using regex with the input eventBy comparing the ASCII co
3 min read
How to change text color depending on background color using JavaScript?
The task is to set the foreground color based on the background color so that it will become visible. Here few of the important techniques are discussed. We are going to use JavaScript. Approach: First, select the random Background color(by selecting random RGB values) or a specific one.Use the YIQ formula to get the YIQ value.Depending on the YIQ
3 min read
How to set the text-color for different elements in CSS ?
Colors are very important to give a good look to the website and engage the users. So, different colored text elements are added to enhance the visuals of the webpage. The CSS color property defines the text color for an HTML element. For setting text-color for different elements in CSS, add the appropriate CSS selector and define the color propert
2 min read
How to append an text message when an input field is modified in jQuery ?
In this article, we will see how to append an element with a text message when an input field is changed in jQuery. To append an element with a text message when the input field is changed, change() and appendTo() methods are used. The change() method is used to detect the change in the value of input fields. This method works only on the “&lt;inpu
2 min read