DEV Community

Cover image for Text live update with Javascript
Lorenzo
Lorenzo

Posted on • Edited on

Text live update with Javascript

Hello World! Today I will explain to you how to have a cool Text live update with Javascript (When user types text update in no time). Since I don't want to do a too-long article I will only focus on core functionality. Even so, I also want to show you some cool tricks at the end. But we've enough talked, now let's focus on the funniest, the code!

Text live update with Javascript:


First of all: HTML

<div class="container">
  <div class="autoUpdateText"></div>
</div>

<form action="/profile" id="form">
  <input type="text" id="input" placeholder="Write here">
</form>
Enter fullscreen mode Exit fullscreen mode

I prefer to use a form input cause you can easily style it how you need. It's also easier to handle in Javascript.

If you want to know more about HTML form input read this cool article (I recommend you to open it on a new page).


This time CSS is crucial. We all agree that basic HTML inputs are awful and repellent

First we style containers:

body {
  font-family: "Alatsi", sans-serif;
  margin: 0;
  overflow: hidden;
  background: white;
  color: black;
}

#form {
  margin-top: 50px;
  display: flex;
  justify-content: center;
  align-content: center;
}

.container {
  display: flex;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

Then text area (input) and text that will follow the input:

#input {
  display: inline-block;
  text-align: center;
  vertical-align: middle;
  width: 600px;
  height: 200px;
  color: #444;
  font-size: 8em;
  background-color: #ddd;
  padding: 8px;
  border: 1px solid #ccc;
  cursor: pointer;
}

.autoUpdateText {
  display: inline-block;
  font-weight: 900;
  font-size: 3.5em;
  line-height: 1em;
  font-family: monospace;
}

.autoUpdateText:hover {
  border-bottom: 0.15em solid white;
// Add here some style on hover
}
Enter fullscreen mode Exit fullscreen mode

Last but not least, the star of the show, Javascript:

Yes you're right, I used the same sentence on this article.

Before we start the party, let's Caching the DOM:

The results show that caching your DOM elements dramatically improves the speed of your code execution. This is clearly seen when comparing tests 3 and 4 where you get a boost from 32,889 to 602,620 operations per second. Site Point

const input = document.querySelector("#input");
const h1 = document.querySelector(".autoUpdateText");
const form = document.querySelector("#form");
countLetters = 0;
maxLineCharacters = 78;
Enter fullscreen mode Exit fullscreen mode

You will see soon why I created countLetters and maxLineCharacters variables.

Now we will add two event listener, first a prevent default to handle a possible user click on Enter:

form.addEventListener("submit", function (e) {
  e.preventDefault();
});
Enter fullscreen mode Exit fullscreen mode

Then an input event listener, everytime user enter a new letter code will run:

input.addEventListener("input", function (e) {
  countLetters = h1.innerHTML.length;
    if (countLetters < maxLineCharacters) {
        h1.innerHTML = input.value;
    } else if (countLetters % maxLineCharacters == 0 && countLetters != 0) {
        inputValue = input.value;
        h1.innerHTML += "<br>";
        row = h1.innerHTML;
        input.value = "";
        h1.innerHTML = row + inputValue;
  } else {
        h1.innerHTML = row + input.value;
    }
});
Enter fullscreen mode Exit fullscreen mode

It may seem long and winding at first look, but I assure you that a line-by-line explanation will quickly make you understand.

countLetters = h1.innerHTML.length;
First, we update countLetters variable to be the length of the h1 (where input will be displayed). We can't have a static variable (adding +1 every time user adds a letter) because we will change the length of the text to handle other possible errors.


I added all the following code principally for two reasons, first because HTML text inputs have a limit of 100 characters and also because we need to perform some operations when a user writes a determined number of characters, such as adding a line break.

if (countLetters < maxLineCharacters) {
    h1.innerHTML = input.value;
Enter fullscreen mode Exit fullscreen mode

The first 78 (you can change this number above) characters will just update o client side, no difficulty.

     } else if (countLetters % maxLineCharacters == 0
Enter fullscreen mode Exit fullscreen mode

Check if countLetters is a multiple of 78 to be able to add a line break every 78 letters.

&& countLetters != 0) I added this part to prevent the first character from not showing on an even number.

inputValue = input.value;
First we save input value in a variable

h1.innerHTML += "<br>";
Then we add a line break to the h1

row = h1.innerHTML;
We save h1 with line break in a variable

input.value = "";
We clear input value (so user can type infinitely)

h1.innerHTML = row + inputValue;
And we update another time the h1 will all the variable before

else { h1.innerHTML = row + input.value; }
Last part, when count is greater than 78 and not a multiple of 78 we display previous rows + new values entered.

Simple as that, It's not data (rocket) science.


You can have here a live preview (in case you missed something):
Click Me


I think I will do another article on that, maybe telling you how to add a complete typewriter effect, how to capitalize all text when user checks a checkbox, or how to add a cursor effect when you write. If you're interested, be sure to smash that like button.

Hope this helped and thanks for reading!


Check this article about how to write CSS like a pro!

Or this one: The ultimate compilation of Cheat sheets (100+) - 🎁 / Roadmap to dev 🚀


Subscribe to our newsletter!

A loooong, and fun, weekly recap for you
Free PDF version of my articles
Highly customizable inbox
That's --> free <-- and you help me!

Top comments (4)

Collapse
 
debaditya15 profile image
Debaditya Malakar

You could have just used onchange html attribute

Collapse
 
lorenzoblog profile image
Lorenzo • Edited

I'm not sure if onchange attribute can work to update content live (onchange occurs when the selection, the checked state or the contents of an element have changed. In some cases, it only occurs when the element loses the focus or when pressing return (Enter) and the value has been changed. rakshasingh.weebly.com/blog/what-i...)
I also need having h1 and input selected allows us to perform more advanced operations (like Typewriter effect).
Say me if I'm wrong. Thanks for the comment

Collapse
 
hatemhosny profile image
Hatem Hosny

Nice article
This can also be achieved by contenteditable attribute
developer.mozilla.org/en-US/docs/W...

Collapse
 
lorenzoblog profile image
Lorenzo

Thanks for the comment! I did not know this attribute.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.