javascript character count

Hello guys in this tutorial we will create character count using HTML CSS & JavaScript

First we need to create two files index.html and style.css then we need to do code for it.

Step:1

Add below code inside index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript input text counter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta https-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
  </head>
  <body>
    <div class="field_outer">
      <div class="field">
        <textarea name="textarea" id="the-textarea" maxlength="100" placeholder="Enter your message..."></textarea>
        <div class="length_outer" id="the-count">
          <div id="current">0</div>
          <div id="maximum">/ 100</div>
        </div>
      </div>
    </div>
    <script type="text/javascript">
      $('textarea').keyup(function () {
        var charCout = $(this).val().length,
            current = $("#current"),
            maximum = $("#maximum"),
            theCount = $("#the-count");

            current.text(charCout);
            if (charCout == 100) { 
              alert("Max Limit 100");
            }
            if (charCout < 30) {
              current.css("color", "#666");
            }
            if (charCout > 60 && charCout < 80) {
              current.css("color", "#8a4343");
            }
            if (charCout > 80 && charCout < 90) {
              current.css("color", "#bd3131");
            }
            if (charCout >= 90) {
              maximum.css("color", "#da1515");
              current.css("color", "#da1515");
              theCount.css("font-weight", "bold");
            }else {
              maximum.css("color", "#000");
              theCount.css("font-weight", "normal");
            }                
      })
    </script>
  </body>
</html>

Step:2

Then we need to add code for style.css which code i provide in below screen.

* {
  padding: 0;
  margin: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
.field_outer {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
textarea#the-textarea {
    font-size: 18px;
    padding: 10px 20px;
    outline: 0;
    border: 1px solid #4b00ff;
    height: 150px;
    min-width: 320px;
}
.length_outer {
    position: absolute;
    bottom: 5px;
    left: 1px;
    font-size: 12px;
    color: #000;
    background: #f1f2f3;
    display: flex;
    padding: 5px;
}
.field {
    position: relative;
}

Output:

Leave a Comment