Creating an Online Words Counter Tool using HTML, CSS, and JS Code

Create an online word counter tool using HTML, CSS, and JavaScript with this step-by-step guide.
7 min read

If you want to create a free online word counter tool and learn HTML, CSS, and JavaScript, you'll need some basic coding skills. However, you don't need to know everything about these technologies. By understanding some basic coding concepts and using online resources, you can easily create your own word counter tool.

First things first, we need to create the basic structure with HTML. We’ll set up a simple form where users can paste their text and instantly see the word and character count. Here’s the HTML code to get you started:


notification
The HTML, CSS, and JS codes in this tutorial are all minified, but I'll explain everything in detail.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Word Counter</title>
  <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,900' rel='stylesheet' type='text/css'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <div class="container">
    <h1>Word Counter</h1>
    <textarea placeholder="Enter your text here..."></textarea>
    <div class="output row">
      <div>Characters: <span id="characterCount">0</span></div>
      <div>Words: <span id="wordCount">0</span></div>
    </div>
    <div class="output row">
      <div>Sentences: <span id="sentenceCount">0</span></div>
      <div>Paragraphs: <span id="paragraphCount">0</span></div>
    </div>
    <div class="output row">
      <div>Reading Time: <span id="readingTime">0</span></div>
      <div id="readability">Show readability score.</div>
    </div>
    <div class="keywords">Top keywords:
      <ul id="topKeywords"></ul>
    </div>
  </div>
  <script src="./script.js"></script>
</body>
</html>

  
Understanding the HTML Code:
This HTML code sets up the framework for our Word Counter web app. It includes a text area for user input and uses JavaScript to dynamically count and display the number of words, characters, sentences, paragraphs, reading time, and top keywords entered.

In HTML, the <textarea> element allows users to type or paste text. We use JavaScript in the script.js file to count words, characters, sentences, and paragraphs in the entered text.

Characters: This code counts all characters entered into the <textarea> element, including spaces and special characters.

Words: This code counts the words entered in the input field. Each space indicates a new word, but spaces and special characters are not counted as words.

Sentences: This code counts the number of sentences based on the number of periods (full stops) in the text.

Paragraphs: This code counts paragraphs by detecting new lines in the text.

Reading Time: This code estimates the average reading time based on the text's length and a standard reading speed.

Top Keywords: This code identifies and counts the most frequently used words, displaying them as top keywords.

Step 2: Style the Form Using CSS. Now that we've set up the HTML structure, let's add some styling with CSS. Here's the CSS code:

 html {
  box-sizing: border-box;
  user-select: none;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
body {
  width: 700px;
  margin: 0 auto;
  background-color: #FAFAFA;
  font-family: 'Source Sans Pro', sans-serif;
  color: #111;
}
.container {
  margin: 2% auto;
  padding: 15px;
  background-color: #FFFFFF;
  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.2);
}
h1 {
  font-size: 3rem;
  font-weight: 900;
  text-align: center;
  margin: 1% 0 3%;
}
textarea {
  width: 100%;
  height: 250px;
  padding: 10px;
  border: 1px solid #d9d9d9;
  outline: none;
  font-size: 1rem;
  resize: none;
  line-height: 1.5rem;
}
textarea:hover {
  border-color: #C0C0C0;
}
textarea:focus {
  border-color: #4D90FE;
}
.output.row {
  width: 100%;
  border: 1px solid #DDD;
  font-size: 1.4rem;
  margin: 1% 0;
  background-color: #F9F9F9;
}
.output.row div {
  display: inline-block;
  width: 42%;
  padding: 10px 15px;
  margin: 1%;
}
.output.row span {
  font-weight: bold;
  font-size: 1.5rem;
}
#readability {
  width: 52%;
  font-weight: bold;
  cursor: pointer;
}
#readability:hover {
  background-color: #4D90FE;
  color: #FFF;
  border-radius: 2px;
}
.keywords {
  display: none;
  margin: 4% 0 0;
  font-size: 2rem;
  font-weight: 900;
}
.keywords ul {
  font-weight: 400;
  border: 1px solid #DDD;
  font-size: 1.4rem;
  background-color: #F9F9F9;
  margin: 2% 0;
}
.keywords li {
  display: inline-block;
  width: 44%;
  padding: 10px;
  margin: 1%;
}

Step 3: Write The Js Code To Count The Words The Final Step Is To Write The Js Code To Count The Number Of Words And Characters In The Text Area. Here's The Js Code


  "use strict";
var input = document.querySelectorAll("textarea")[0],
    characterCount = document.querySelector("#characterCount"),
    wordCount = document.querySelector("#wordCount"),
    sentenceCount = document.querySelector("#sentenceCount"),
    paragraphCount = document.querySelector("#paragraphCount"),
    readingTime = document.querySelector("#readingTime"),
    readability = document.querySelector("#readability"),
    keywordsDiv = document.querySelectorAll(".keywords")[0],
    topKeywords = document.querySelector("#topKeywords");

input.addEventListener("keyup", function () {
    characterCount.innerHTML = input.value.length;
    var words = input.value.match(/\b[-?(\w+)?]+\b/gi);
    wordCount.innerHTML = words ? words.length : 0;
    var sentences = input.value.split(/[.|!|?]+/g);
    sentenceCount.innerHTML = sentences.length - 1;
    var paragraphs = input.value.replace(/\n$/gm, "").split(/\n/);
    paragraphCount.innerHTML = paragraphs.length;
    var time = Math.floor(60 * (words ? words.length : 0) / 275);
    readingTime.innerHTML = time > 59 ? Math.floor(time / 60) + "m " + (time % 60) + "s" : time + "s";
    
    var keywordArray = [];
    var stopWords = ["a", "able", "about", "above", "according", "across", "actually", "after", "again", "against", "all", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "an", "and", "another", "any", "anybody", "anyone", "anything", "anyway", "anywhere", "are", "aren", "arent", "around", "as", "at", "away"];
    if (words) {
        words.forEach(function (word) {
            if (stopWords.indexOf(word.toLowerCase()) === -1) {
                keywordArray.push(word.toLowerCase());
            }
        });
    }
    var keywordCounts = {};
    keywordArray.forEach(function (word) {
        keywordCounts[word] = (keywordCounts[word] || 0) + 1;
    });
    var sortedKeywords = Object.keys(keywordCounts).sort(function (a, b) {
        return keywordCounts[b] - keywordCounts[a];
    });
    topKeywords.innerHTML = "";
    sortedKeywords.slice(0, 4).forEach(function (keyword) {
        var listItem = document.createElement("li");
        listItem.innerHTML = "<b>" + keyword + "</b>: " + keywordCounts[keyword];
        topKeywords.appendChild(listItem);
    });
    keywordsDiv.style.display = words ? "block" : "none";
});

This JavaScript code listens for any keypresses in the text area and updates the counts in real time. It uses regular expressions to tally words, sentences, paragraphs, and calculates reading time based on an average reading speed. The code also filters out common stop words to display the top keywords in the text.

The code first sets up variables to hold references to the HTML elements that will display the various counts and calculations. It then sets up an event listener to run whenever a key is pressed in the text area. This ensures that the displayed statistics update dynamically as the user types.

The code uses regular expressions to count the number of words, sentences, and paragraphs in the text area. It also calculates the reading time based on an average reading speed of 275 words per minute. Finally, it finds the top keywords in the text area by removing stop words and sorting the remaining words by frequency.

The code is well-commented, making it easy to understand what each section does. It also includes a user story at the beginning, which outlines the various features the code should provide.

Step 4: Test the tool Once you have completed all the steps, save the HTML, CSS, and JS files in the same directory and open the HTML file in your browser. Paste some text into the text area and click the "Count Words" button. You should see the number of words and characters displayed below the button

Online Word Counter Tool

Note
Download The Source Code For A Powerful Word Counter Tool By Clicking The Button Below. Let's Make Progress Together.

Conclusion

Creating an online words counter tool using HTML, CSS, and JS code is a simple and easy process. By following the steps outlined in this blog, you can create your own online words counter tool and use it to accurately count the number of words and characters in your documents. Whether you are a student, blogger, or writer, this tool can be a valuable asset in your writing toolkit.

You may like these posts

Post a Comment