Make Your Own Text Editor in 15 Minutes: Practicum Coding Bootcamp

Written by evgeniy-lebedev | Published 2019/12/05
Tech Story Tags: javascript | html | css | programming | tutorial-for-beginners | coding | beginners | practicum-by-yandex

TLDRvia the TL;DR App

It’s not like there aren’t enough text editors. But consider this: with about 60 lines of code (that’s close to nothing), you can make your own secure and stable text editor. It will be pretty simple and won’t have many features, but it will be of your making, even if you barely know how to code.
It sounds like a perfect adventure. 

What I’ll need

HTML — this is the language that is used to structure web pages. Your browser interprets HTML and renders a page based on its instructions. Our text editor will be a web page that will work in your browser. 
JavaScript — this language that allows you to dynamically manipulate things on your webpage, and even build whole web-based apps. Ever heard of Slaсk? Written entirely on JavaScript. Ever seen a web page with snow falling over the text? That snow, too, is JavaScript. 
Localstorage — your browser has a special block of memory that can be used to store data. It is restricted to a page (meaning, each page has its own isolated storage) and doesn’t sync across different devices or browsers. I’ll use this area to store our text. 
Content Editable — some blocks in HTML can have this property, which will allow users to edit what’s inside that block. The changes will only be visible to the user (by default), but there will be changes nevertheless. Later, you can implement synchronization, so that other users see the edits as well. 

How this is going to work

  1. I’ll have a web page that contains an area, or a block. Because I want to keep it simple, I’ll start with no design at all, just bare structure. I’ll refine the visuals in the next version.
  2. That block will be content-editable, meaning you can type into it.
  3. In the background, there will be JavaScript, looking at what’s going on inside the page. I will tell JavaScript to pay attention to whenever I press a key. When I press a key, JavaScript will save to localstorage whatever is in the editable block.
  4. As a final touch, I’ll add some lines of code that tell JavaScript to look for anything in Localstorage once the page loads. This will ensure that our text is recalled when I reload the page. 
The result will be a very simple-looking, yet a functional text editor with auto-save. You can quit and reload your browser, even restart your computer, and your text will stay there. 

Step 1. Housekeeping and groundwork

First, I’ll need an empty HTML page. There is a pinch of wizardry required to tell the browser that the document it’s looking at is a web page. No need to remember this code, I just copied it from an HTML blank page template.
<!DOCTYPE html>
<html> 
<head> 
  <title>My text editor</title>
  <!-- Behold the three lines of wizardry -->
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

  <!-- here will be our block and then the script -->

</body>
</html>

This code literally tells the browser that it’s looking at an HTML page (a web page, that is). It tells the browser the title of this page (the one you’ll see in your tabs), then the language (UTF-8 means Unicode, or basically ‘All languages in the World, I support them all’), then some compliance and technical niceties, and then the body of the page.
The body at this moment is blank. But I’ll need two things in our editor: some headline to tell the user where they are and the editor itself. Let’s add these two lines of code in between the <body> and </body>:
<h2>Text editor with auto-save</h2>
  <div id="editor" style="height: 100%; width: 70%; border: solid; border-width: 1px; padding 15px;"></div>

The first line is heading. H2 stands for ‘Heading of the second level’. In our case, the level doesn’t make sense, but I just like how it looks. 
The second line is a little more complicated. Let’s break it down:
  • div stands for ‘division’, or just a block. Some virtual objects on-page. As such, it means nothing and does nothing, but programmers use divs all the time because they can make divs do all sorts of things. 
  • id="editor" lets me call that div by its name from the script I write
  • style=... sets some boundaries to the div. As such, the div takes as much space as its contents, but since our contents are currently zero, the div will be of zero size, too. So I force it to be 50% of the page’s width and 100% of the page’s height. BE HUGE, I tell the div. I also draw a small border around it, so I can see it. And add a small padding inside the div so that our text doesn’t run up straight to the black box. A page gotta have margins. 
I can also go to the top of the page and add some code to Style. Try to make sense of this yourself, it’s fairly legible. Hint: ‘body’ means ‘all page’:
<style type="text/css">
    body{
      text-align: left;
      margin: 10;
      font-family: Verdana, Arial, sans-serif;
      font-size: 16px;
    }
  </style>

If I save now as an HTML file, I’ll just have a rectangle on white background, and some headline. Nothing will work just yet.

Step 2. Content Editable

I need to make our div content-editable. This is achieved surprisingly easy, you just add a property to the div:
  <div id="editor" contenteditable="true" style="height: 100%; width: 70%; border: solid; border-width: 1px; padding 15px;"></div>
You heard it right. You just say contenteditable="true". Now save and reload, and WHOA YOU CAN TYPE IN THE BOX. If you reload the page, though, all you’ve written will be gone. Let’s fix that. 

Step 3. JavaScript lurking

To add JavaScript behavior to page, I need to put the code between the <script>...</script> tags. I can also write the entire script in a separate file and link to it from our page, but with the script this small, it makes no sense. I’ll just write our entire program inside the web page. 
What I want now:
  1. Listen to key presses
  2. When a key is pressed, save the contents of our div by the name of ‘Editor’ into Local Storage. Name that local storage item ‘text_in_editor’ for future reference
See how this code looks:
<script>
    document.addEventListener('keydown', function(e) {
      localStorage.setItem('text_in_editor',   document.getElementById('editor').innerHTML);
    });
  </script>

The last part can be confusing with all the dots. JavaScript can be ugly like that. If I translated it, though, it would mean this: ‘In Local storage, create an item. Call that item ‘text_in_editor’. For its contents, go here: document, in the document, get an element with id ‘editor’, and look inside its HTML. See that HTML? Get it and put it in local storage’
If you save the code and reload the page now, nothing will seem to work though. If you reload your text editor, you lose your text. The reason is this: our script saves the text into Local storage, but it doesn’t retrieve anything from it at any time: not at loading, not at refreshing. It’s like buying canned goods, storing them in a cabinet and never actually eating them. Also, the cabinet is infinitely huge and invisible.
So at this point, everything is actually working, just not in a way that’s useful to me. That’s not surprising since I didn’t tell it to work in a way that’s useful. Let’s fix this in step 4.

Step 4. Retrieve from local storage

Before I add an event listener in JavaScript, let’s run this algorithm:
  1. See if there’s anything in local storage under the name ‘text_in_editor’.
  2. If there is something, load it
  3. If not, whatever, move on
Here is how this reads in JavaScript:
if (localStorage.getItem('text_in_editor') !== null) {
        document.getElementById('editor').innerHTML = localStorage.getItem('text_in_editor');
      }


The last line means this: ‘Go to Local storage, get the item with the name text_in_editor, take its contents and put those contents into the document, inside the element with id editor’. The ‘put inside’ part is done by the equation sign =. In JavaScript, equation means assign, or simply put somewhere. For example:
someNumber = 5; // this means put ‘5’ into the memory slot under the name 'someNumber'
otherNumber = someNumber; //this means take whatever’s in someNumber and put that into the memory under the name otherNumber. Basically it’s copying

Now look again at our code of the text editor. Observe what is put where. Look at the parts to the right and to the left of the equation sign:
document.getElementById('editor').innerHTML = localStorage.getItem('text_in_editor');
o the right is what is being assigned (from where I take stuff). To the right is where I assign, or where I put that stuff. 
As a side note, I AM DONE :-)
The code will work the way I wanted, check this out: 

Final code

Copy, paste in a regular text editor, save as HTML and open in browser, and voilá! There is the text box, you can type in it, it saves to Local storage, then when you reload the page, it loads from local storage.
<!DOCTYPE html>
<html> 
<head> 
  <title>My text editor</title>
<!-- The three following lines — trust me — we need this-->
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 
  <!-- some minimal design (not necessary)-->
  <style type="text/css">
    body{
      text-align: left;
      margin: 10;
      font-family: Verdana, Arial, sans-serif;
      font-size: 16px;
    }
  </style>

</head>
<body>

  <!-- heading -->
  <h2>Text editor with auto-save</h2>
 
  <!-- here be our editable area →
  <div id="editor" contenteditable="true" style="height: 100%; width: 70%; border: solid; border-width: 1px; padding 15px;"></div>
 
  <!-- Here be our script -->

  <script>

    // If there's anything in the storage
    if (localStorage.getItem('text_in_editor') !== null) {
 
        // ...then show it
        document.getElementById('editor').innerHTML = localStorage.getItem('text_in_editor');
      }

    // listen to key presses
    document.addEventListener('keydown', function(e) {

      // once a key is pressed, save whatever's in our box to localstorage
      localStorage.setItem('text_in_editor', document.getElementById('editor').innerHTML);
    });
  </script>
 
</body>
<!-- That's all folks -->
</html>

What’s next

Oh, next I’ll make this thing beautiful. Stay tuned!

Written by evgeniy-lebedev | Chief Marketing Officer Practicum Coding Bootcamp, edtech expert, practicum.com
Published by HackerNoon on 2019/12/05