Open In App

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

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



Last Updated : 18 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads