Create an Inline Text Editor With the contentEditable Attribute

by:

Web Development

[ad_1]

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 and 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.

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:

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.

You can put this code in a <script> tag at the bottom of the <body> tag. We use querySelectorAll() to store all 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 is 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.

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.

You can also save the changes on every keydown event.

In this tutorial I am 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, lets add a toolbar. First, we need to add some HTML. Add this snippet to the top of the <body> tag.

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

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 functional for H2s, you can simply change the element selector and the HTML inserted.

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.

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 it’s 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, a freelancer, and an open-source contributor.

Leave a Reply

Your email address will not be published. Required fields are marked *