# Create an Inline Text Editor With the contentEditable Attribute

Creating an inline editor requires effort. You begin by switching the element to be edited with an input or textarea field. For a seamless user experience, you might also have to use some CSS in order to match the styling of swapped elements to the original one. Once the user is done editing, you will again have to switch the elements after copying all the content to the original ones.

The contentEditable attribute makes this task a lot easier. All you have to do is set this attribute to true, and standard HTML5 elements will become editable. In this tutorial, we will create an inline rich text editor based on this feature.

## The Basics

This attribute can take three valid values. These are true, false, and inherit. The value true indicates that the element is editable. An empty string will also evaluate to true. false indicates that the element is not editable. The value inherit is the default value. inherit indicates that an element will be editable if its immediate parent is editable. This implies that if you make an element editable, all its children (not just immediate ones) will become editable as well, unless you explicitly set their contentEditable attribute to false.

You can change these values dynamically with JavaScript. If the new value is none of the three valid ones, then it throws a SyntaxError exception.

## Creating the Editor

To create the inline editor, you need to have the ability to change the value of the contentEditable attribute whenever a user decides to edit something.

While toggling the contentEditable attribute, it is necessary to know what value the attribute holds currently. To accomplish that, you can use the isContentEditable property. If isContentEditable returns true for an element, then the element is currently editable—otherwise it is not. We will use this property shortly to determine the state of various elements in our document.

First, we need to create a directory called contenteditable-editor. Inside that, create a new file called index.html. You can use this as a skeleton for your HTML file.

 1   2   3   4   5   6   7  Text Editor  8   9   10  

The first step in building the editor is the creation of a button to toggle editing and some editable elements. Inside the <body> element, put this:

 1   2 3 
 4 

 5 

Last Edited By - Monty Shokeen

 6 

Some content that needs correction.

 7 


Each element that we intend to keep editable needs to have its own unique Id. This will be helpful when we have to save the changes or retrieve them later to replace the text inside each element.

The following JavaScript code handles all the editing and saving.

 1 const editBtn = document.getElementById('editBtn');  2 const editables = document.querySelectorAll('#title, #author, #content')  3 4 editBtn.addEventListener('click', function(e) {  5  if (!editables[0].isContentEditable) {  6  editables[0].contentEditable = 'true';  7  editables[1].contentEditable = 'true';  8  editables[2].contentEditable = 'true';  9  editBtn.innerHTML = 'Save Changes';  10  editBtn.style.backgroundColor = '#6F9';  11  } else {  12  // Disable Editing  13  editables[0].contentEditable = 'false';  14  editables[1].contentEditable = 'false';  15  editables[2].contentEditable = 'false';  16  // Change Button Text and Color  17  editBtn.innerHTML = 'Enable Editing';  18  editBtn.style.backgroundColor = '#F96';  19  // Save the data in localStorage  20  for (var i = 0; i < editables.length; i++) {  21  localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);  22  }  23  }  24 }); 

You can put this code in a <script> tag at the bottom of the <body> tag. We use querySelectorAll() to store all the editable elements in a variable. This method returns a NodeList which contains all the elements in our document that are matched by specified selectors. This way, it's easier to keep track of editable elements with one variable. For instance, the title of our document can be accessed by using editables[0], which is what we will do next.

Next, we add an event listener to our button's click event. Every time a user clicks on the Edit Document button, we check if the title is editable. If it is not editable, we set the contentEditable property on each of the editable elements to true. Moreover, the text 'Edit Document' changes to 'Save Changes'. After users have made some edits, they can click on the 'Save Changes' button and the changes made can be saved permanently.

If the title is editable, we set the contentEditable property on each of the editable elements to false. At this point, we can also save the content of our document on the server to retrieve later or synchronize the changes to a copy that exists somewhere else. In this tutorial, I am going to save everything in localStorage instead. When saving the value in localStorage, I am using the Id of each element to make sure that I don't overwrite anything.

## Retrieving Saved Content

If you make changes to any of the elements in the previous demo and reload the page, you will notice that the changes you made are gone. This is because there is no code in place to retrieve the saved data. Once the content has been saved in localStorage, we need to retrieve it later when a user visits the webpage again.

 1 if (typeof(Storage) !== "undefined") {  2 3  if (localStorage.getItem('title') !== null) {  4  editables[0].innerHTML = localStorage.getItem('title');  5  }  6   7  if (localStorage.getItem('author') !== null) {  8  editables[1].innerHTML = localStorage.getItem('author');  9  }  10   11  if (localStorage.getItem('content') !== null) {  12  editables[2].innerHTML = localStorage.getItem('content');  13  }  14 } 

The code above checks if the title, author, or content already exist in localStorage. If they do, we set the innerHTML of the respective elements to the retrieved values.

## Auto-Saving

To make the editor more user-friendly, we should add auto-saving. The first method automatically saves your work every five seconds.

 1 setInterval(function() {  2  for (var i = 0; i < editables.length; i++) {  3  localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);  4  }  5 }, 5000); 

You can also save the changes on every keydown event.

 1 document.addEventListener('keydown', function(e) {  2  for (var i = 0; i < editables.length; i++) {  3  localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);  4  }  5 }); 

In this tutorial, I'm sticking with the latter method. You are free to trigger auto-save based on any event that seems appropriate in your projects.

## Creating a Toolbar

Now, we need to make it easy for people to insert new headings and other formatting elements. To do this, let's add a toolbar. First, we need to add some HTML. Add this snippet to the top of the <body> tag.

 1 
 2   3   4 


Now, let's make that actually do something. We need to add a click event that inserts a heading into the content block.

 1 document.querySelector("#addh1").addEventListener("click", function (e) {  2  const text = prompt(  3  "What text do you want the heading to have?",  4  "Heading"  5  );  6  editables[2].innerHTML = editables[2].innerHTML +

${text} ;  7 });  This attaches a click event to the H1 button, which prompts you to enter text using the prompt() function and puts that text in a header inside the content block. You can also edit the header just like normal text if you want. To add this function for H2s, you can simply change the element selector and the HTML inserted.  1 document.querySelector("#addh2").addEventListener("click", function (e) {  2  const text = prompt(  3  "What text do you want the heading to have?",  4  "Heading"  5  );  6  editables[2].innerHTML = editables[2].innerHTML + ${text}

;  7 }); 

You can easily extend this to other elements, like bold text and underlining, just by creating a new line and a version of the above code with the new selector and different HTML tags inserted.

## Styling the Editor

Currently, the editor has no CSS. You can style it however you want, but we also have a style premade for you. If you want the same style as I used in the code pens, you can use this CSS.

 1 body {  2  font-family: Arial;  3  font-size: 1.3em;  4  line-height: 1.6em;  5 }  6 7 .headline {  8  font-size: 2em;  9  text-align: center;  10 }  11 12 #wrapper {  13  width: 600px;  14  background: #fff;  15  padding: 1em;  16  margin: 1em auto;  17  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);  18  border-radius: 3px;  19 }  20 21 button {  22  border: none;  23  padding: 0.8em;  24  background: #f96;  25  border-radius: 3px;  26  color: white;  27  font-weight: bold;  28  margin: 0 0 1em;  29 }  30 31 button:hover,  32 button:focus {  33  cursor: pointer;  34  outline: none;  35 }  36 37 #editor {  38  padding: 1em;  39  background: #e6e6e6;  40  border-radius: 3px;  41 } 

## Testing

To test your work, you can use something like serve. To use serve, you just run npm i -g serve and then run serve inside the directory containing your work. serve will automatically start a webserver containing your HTML file, which you can navigate to by clicking the link printed.

## Editing the Entire Page With Design Mode

contentEditable is useful when you have to edit a few elements on a webpage. When the content of all or almost all the elements on a webpage has to be changed, you can use the designMode property. This property is applicable to the whole document. To turn it on and off, you use document.designMode = 'on'; and document.designMode = 'off'; respectively.

This will prove valuable in situations where you are the designer and someone else is the content creator. You provide them with a design and some dummy text. Later, they can replace it with real content. To see designMode in action, open up the console tab in your browser's developer tools. Type document.designMode = 'on'; into the console and press Enter. Everything on this page should be editable now.

## Final Thoughts

The contentEditable attribute is convenient in situations like quickly editing articles or enabling users to edit their comments with a single click. This feature was first implemented by IE 5.5. Later, it was standardized by WHATWG. The browser support is also very good. All major browsers besides Opera Mini support this attribute.

JavaScript has become one of the standard languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

This tutorial covered the basics of the contentEditable attribute and how it can be used to create a basic inline text editor, as well as how to add buttons for rich formatting.

This post has been updated with contributions from Jacob Jackson. Jacob is a web developer, technical writer, freelancer, and open-source contributor.