The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a live word counter

To build a live word counter, you can use a combination of HTML, CSS, and JavaScript. Here’s an example of a simple live word counter that updates as the user types:

HTML:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Live Word Counter</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Live Word Counter</h1> <textarea id="textInput" placeholder="Start typing..." rows="10" cols="50"></textarea> <div class="counter"> <p>Word Count: <span id="wordCount">0</span></p> </div> </div> <script src="script.js"></script> </body> </html>

CSS (styles.css):

css
body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f4f4f9; margin: 0; } .container { text-align: center; } textarea { width: 100%; max-width: 600px; margin-top: 20px; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; resize: none; } .counter { margin-top: 20px; font-size: 18px; }

JavaScript (script.js):

javascript
document.getElementById('textInput').addEventListener('input', function() { const text = this.value.trim(); const wordCount = text.split(/s+/).filter(function(word) { return word.length > 0; }).length; document.getElementById('wordCount').textContent = wordCount; });

How it works:

  • HTML: Defines the structure with a textarea for user input and a div to display the word count.

  • CSS: Provides basic styling to center the elements and give them a clean appearance.

  • JavaScript: Listens for input events on the textarea, counts the words by splitting the text on spaces and counting non-empty parts, and updates the word count dynamically.

To use this, simply create the three files (index.html, styles.css, and script.js), and open the HTML file in a web browser. As you type in the textarea, the word count will automatically update below it.

Let me know if you’d like further customization or additional features!

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About