Create Word & Character Counter with HTML, CSS, JavaScript (Source Code)

Faraz

By Faraz -

Learn how to create word, character, and paragraph counters using HTML, CSS, and JavaScript. A beginner-friendly guide to boost your web development skills.


Creating Words, Paragraph, and Character Counter with HTML, CSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Word and character counters are essential tools in web development. They help content creators, bloggers, and SEO experts keep track of their content's length and structure. In this guide, we'll show you how to create your own word, character, and paragraph counter using HTML, CSS, and JavaScript.

Prerequisites

Before we dive into the implementation, you'll need the following:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A code editor (e.g., Visual Studio Code).
  • Web browser for testing.

Source Code

Step 1 (HTML Code):

To start, create the basic HTML structure for your word counter. Open your code editor and create an HTML file. Use a simple form to input text, and add an element to display the word and character count.

How to do it:

  1. Open your code editor.
  2. Create an HTML file.
  3. Design a form with a textarea for user input.
  4. Add an element (e.g., a <div>) to display the word and character count.
  5. Link your CSS and JavaScript files.

Let's break down the code step by step:

1. <!DOCTYPE html>: This document type declaration specifies that the document is an HTML5 document.

2. <html lang="en">: This is the opening tag for the HTML document. It declares the document's root element and sets the language attribute to "en" (English). Everything within the document is enclosed within the <html> tags.

3. <head>: This is the head section of the document. It contains metadata and information about the web page but is not visible to the user.

  • <meta charset="UTF-8">: This meta tag specifies the character encoding of the document as UTF-8, which is a widely used character encoding for handling text in various languages.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is used to ensure compatibility with older versions of Internet Explorer. It sets the rendering engine mode for Internet Explorer to "edge mode," which is the most up-to-date rendering mode.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is crucial for responsive web design. It configures the viewport to match the device's width and sets the initial zoom level to 1.0, ensuring that the page scales correctly on different screen sizes.
  • <title>Word Count</title>: This sets the title of the web page to "Word Count," which is typically displayed in the browser's title bar or tab.
  • <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">: This line links to an external stylesheet from Google Fonts, making the "Poppins" font available for use on the web page.
  • <link rel="stylesheet" href="styles.css" />: This line links to an external CSS (Cascading Style Sheets) file named "styles.css" for styling the web page's content.

4. <body>: This is the body section of the document. It contains the visible content of the web page.

5. <h1>Word Counter</h1>: This is a level 1 heading, indicating that the main title of the page is "Word Counter."

6. <div class="container">: This is a container division that groups related elements together.

7. <textarea placeholder="Enter your text here..."></textarea>: This is a text input area where users can enter text. The "placeholder" attribute provides a hint or example text to guide the user.

8. <div class="output-container">: This is another container division for organizing output elements.

  • There are four <div class="output"> elements, each representing a category of output (Words, Characters, Sentences, Paragraphs).
  • Inside each <div class="output"> element, there is a <p> element with a class representing the category (e.g., "words," "characters"). This is a paragraph element used for labeling the output category.
  • Next, there is a <span> element with a custom "data-" attribute (e.g., "data-word-count," "data-character-count"). These spans are intended to display the actual count of words, characters, sentences, and paragraphs.

9. <script src="script.js" defer></script>: This line includes an external JavaScript file named "script.js." The "defer" attribute tells the browser to download the script file while parsing the HTML and execute it only after the document is fully parsed.

Step 2 (CSS Code):

Making your counter visually appealing is crucial. CSS can help you style the form, text area, and result display.

How to do it:

  1. Create a CSS file.
  2. Style the form and textarea to make them user-friendly.
  3. Use CSS to format the display element for a clear presentation.

I'll explain each part of the code step by step:

1. * selector:

  • margin: 0; sets the margin of all HTML elements to 0.
  • padding: 0; sets the padding of all HTML elements to 0.
  • box-sizing: border-box; makes sure that the width and height of elements include both their content and padding, without expanding due to borders.

2. body selector:

  • font-family: Poppins; sets the font for the entire webpage to "Poppins."
  • background-color: #090909; sets the background color of the body to a very dark gray (#090909).
  • color: #a09fa4; sets the text color to a light gray (#a09fa4).
  • height: 100vh; sets the height of the body to 100% of the viewport height.
  • display: flex; makes the body a flex container.
  • flex-direction: column; arranges the child elements in a column layout.
  • justify-content: center; centers the content vertically.
  • gap: 5rem; adds a gap of 5rem (5 times the root font size) between child elements within the body.

3. .container class selector:

  • width: 100%; sets the container's width to 100% of its parent element.
  • max-width: 46rem; sets a maximum width of 46rem for the container, creating a responsive layout.
  • background-color: white; sets the background color of the container to white.
  • border-radius: 0.5rem; rounds the corners of the container with a 0.5rem radius.
  • margin: 0 auto; centers the container horizontally on the page.
  • display: flex; makes the container a flex container.
  • flex-direction: column; arranges the child elements in a column layout within the container.
  • gap: 1rem; adds a gap of 1rem between child elements within the container.

4. textarea selector:

  • resize: none; disables the ability to resize the textarea.
  • width: 100%; sets the width of the textarea to 100% of its parent container.
  • height: 250px; sets the initial height of the textarea to 250 pixels.
  • padding: 1rem; adds 1rem of padding inside the textarea.
  • color: #242e3e; sets the text color inside the textarea to a dark blue-gray (#242e3e).
  • font: inherit; inherits the font from the parent element.
  • font-size: 1rem; sets the font size to 1rem.
  • border-radius: inherit; inherits the border radius from the parent container.
  • outline: none; removes the default outline style.
  • border: 0; removes the border of the textarea.

5. .output-container class selector:

  • display: flex; makes the output container a flex container.
  • align-items: center; centers the child elements vertically.
  • justify-content: center; centers the child elements horizontally.
  • gap: 3.5rem; adds a gap of 3.5rem between child elements within the output container.
  • padding: 1rem; adds 1rem of padding around the container.
  • border-top: 1px solid gray; adds a 1px solid gray border at the top of the container.

6. .output class selector:

  • display: flex; makes the output container a flex container.
  • flex-direction: column; arranges the child elements in a column layout.
  • text-align: center; centers the text horizontally.

7. .output p selector:

  • font-size: 0.8rem; sets the font size of paragraphs inside the output container to 0.8rem.
  • text-transform: uppercase; transforms the text to uppercase.
  • letter-spacing: 1px; adds 1px of letter spacing.

8. .output span selector:

  • font-size: 1.6rem; sets the font size of spans inside the output container to 1.6rem.
  • font-weight: 700; sets the font weight to bold (700).
  • color: #242e3e; sets the text color to a dark blue-gray (#242e3e).

9. h1 selector:

  • font-size: 2.6rem; sets the font size of h1 headings to 2.6rem.
  • color: white; sets the text color to white.
  • text-align: center; centers the text horizontally within the container.
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Poppins;
  background-color: #090909;
  color: #a09fa4;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 5rem;
}

.container {
  width: 100%;
  max-width: 46rem;
  background-color: white;
  border-radius: 0.5rem;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

textarea {
  resize: none;
  width: 100%;
  height: 250px;
  padding: 1rem;
  color: #242e3e;
  font: inherit;
  font-size: 1rem;
  border-radius: inherit;
  outline: none;
  border: 0;
}

.output-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3.5rem;
  padding: 1rem;
  border-top: 1px solid gray;
}

.output {
  display: flex;
  flex-direction: column;
  text-align: center;
}

.output p {
  font-size: 0.8rem;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.output span {
  font-size: 1.6rem;
  font-weight: 700;
  color: #242e3e;
}

h1 {
  font-size: 2.6rem;
  color: white;
  text-align: center;
} 

Step 3 (JavaScript Code):

The core functionality of your word and character counter comes from JavaScript. You'll need to implement code to count words and characters in real-time.

How to do it:

  1. Create a JavaScript file.
  2. Write code to count words and characters as the user types.
  3. Update the display element with the counts.
  4. Handle any edge cases or issues.

This JavaScript code is designed to perform real-time analysis of text input in a textarea element on a web page and display statistics like word count, character count, sentence count, and paragraph count. Here's a breakdown of what the code does:

1. It starts by selecting the textarea element on the web page and four other elements with attributes [data-word-count], [data-character-count], [data-sentence-count], and [data-paragraph-count]. These are presumably elements where the corresponding statistics will be displayed.

2. It sets up an event listener that listens for the "input" event on the textarea. This means that whenever the user types or modifies the text in the textarea, the event listener function will be executed.

3. Inside the event listener function:

  • a. It checks if the input.value (the text entered into the textarea) is not empty. If it's not empty, it proceeds to count various statistics.
  • b. Word Count: It splits the input text into an array of words by splitting it at spaces (" "), and then it uses the filter function to remove any empty strings in the array (which might occur due to multiple spaces). It counts the length of the filtered array to determine the number of words and updates the corresponding element's inner text with this count.
  • c. Character Count: It simply counts the total number of characters in the input text and updates the corresponding element.
  • d. Sentence Count: It splits the input text into an array of sentences by using a regular expression that matches periods (.) or exclamation points (!). It counts the length of this array and subtracts 1 to account for cases where the text doesn't end with a period (e.g., the last sentence). The result is then updated in the corresponding element.
  • e. Paragraph Count: It splits the input text into an array of paragraphs by splitting it at newline characters ("\n"). It uses the filter function to remove any empty or whitespace-only paragraphs. The length of the filtered array gives the paragraph count, which is updated in the corresponding element.

4. If the input.value is empty (no text is entered), it sets all the statistic counts to 0. This ensures that if the user deletes all the text, the displayed statistics are reset to zero.

const input = document.querySelector("textarea");
const wordCount = document.querySelector("[data-word-count]");
const characterCount = document.querySelector("[data-character-count]");
const sentenceCount = document.querySelector("[data-sentence-count]");
const paragraphCount = document.querySelector("[data-paragraph-count]");

input.addEventListener("input", function () {
  if (input.value) {
    // Count Words
    const wordsArray = input.value.split(" ").filter((word) => word !== "");
    wordCount.innerText = wordsArray.length;

    // Count Characters
    characterCount.innerText = input.value.length;

    // Count Sentences
    const sentenceArray = input.value.split(/[.!]/);

    sentenceCount.innerText = sentenceArray.length - 1;

    // Count Paragraph
    const paragraphArray = input.value
      .split("\n")
      .filter((p) => p.trim() !== "");

    paragraphCount.innerText = paragraphArray.length;
  } else {
    wordCount.innerText =
      characterCount.innerText =
      sentenceCount.innerText =
      paragraphCount.innerText =
        0;
  }
});

Final Output:

Creating Words, Paragraph, and Character Counter with HTML, CSS, and JavaScript.gif

Conclusion:

By following this guide, you've learned how to create a word, character, and paragraph counter with HTML, CSS, and JavaScript. This tool is invaluable for content creators and web developers. Experiment with styles and functionalities to create your custom word counter, and enhance your web development skills. Happy coding!

Code by: Parth Johar

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post