Friday, May 24, 2024
HomeCSSHow to Create a Real Time Character Counter using JavaScript | Beginner...

How to Create a Real Time Character Counter using JavaScript | Beginner JavaScript Project

Hello Future Coders, In this article we are going to learn how to create a real time character counter using html, css and javascript. Below I have provided a step by step video tutorial as well as the source code of this project for you to build this project.

Build a Real Time Character Counter | JavaScript Project Video Tutorial

Real Time Character Counter using HTML, CSS and JavaScript | Source Code

For this project create three files: index.html, styles.css and script.js. Dont forget to link them with html. Follow the below steps to complete the project

Step 1: Adding HTML

Create a container div and add an h2 tag for the heading, textarea where the user will write and finally a div with id counter to show the number of characters.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>8 Real Time Character Counter</title>
    <link rel="stylesheet" href="styles.css" />
    <div class="container">
      <h2>Real Time Character Counter</h2>
      <textarea id="textarea"></textarea>
      <div id="counter">0 Characters</div>

    <script src="script.js"></script>

Step 2: Styling the project

Follow the below css styles to keep the project simple.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;

body {
  background-color: #ebebeb;
  max-width: 900px;
  margin: 0 auto;
  padding: 5rem;

.container {
  background-color: #fff;
  padding: 2rem;
  border-radius: 1rem;
  box-shadow: rgba(0, 0, 0, 0.08) 0px 4px 12px;

#textarea {
  font-size: 1rem;
  width: 100%;
  height: 10rem;
  margin: 1rem 0rem;
  padding: 1rem;

#counter {
  font-size: 1.5rem;
  font-weight: bold;

Step 3: Adding JavaScript

First lets get our DOM elements and store them inside the variables textarea and counter. For the textarea we need to add an event listener so that it keeps track of when the user types or adds inputs. So once the user starts typing, we will get the content of the textarea and calculate the length and store it in the count variable.

Finally display the count value and update the DOM.

var textarea = document.querySelector("#textarea")
var counter = document.querySelector("#counter")

textarea.addEventListener("input", function () {
  var count = textarea.value.length
  counter.innerHTML = count + " Characters"

That’s it. Hope you guys enjoyed this tutorial and don’t forget to check our other tutorials as well. Download the source code from below.



Please enter your comment!
Please enter your name here

Latest Posts