This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
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.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Text Editor</title> </head> <body></body> </html>
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:
<button id="editBtn" type="button">Edit Document</button> <div id="editor"> <h1 id="title">A Nice Heading.</h1> <p>Last Edited By - <span id="author">Monty Shokeen</span></p> <p id="content">Some content that needs correction.</p> </div>
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.
const editBtn = document.getElementById('editBtn'); const editables = document.querySelectorAll('#title, #author, #content') editBtn.addEventListener('click', function(e) { if (!editables[0].isContentEditable) { editables[0].contentEditable = 'true'; editables[1].contentEditable = 'true'; editables[2].contentEditable = 'true'; editBtn.innerHTML = 'Save Changes'; editBtn.style.backgroundColor = '#6F9'; } else { // Disable Editing editables[0].contentEditable = 'false'; editables[1].contentEditable = 'false'; editables[2].contentEditable = 'false'; // Change Button Text and Color editBtn.innerHTML = 'Enable Editing'; editBtn.style.backgroundColor = '#F96'; // Save the data in localStorage for (var i = 0; i < editables.length; i++) { localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML); } } });
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.
if (typeof(Storage) !== "undefined") { if (localStorage.getItem('title') !== null) { editables[0].innerHTML = localStorage.getItem('title'); } if (localStorage.getItem('author') !== null) { editables[1].innerHTML = localStorage.getItem('author'); } if (localStorage.getItem('content') !== null) { editables[2].innerHTML = localStorage.getItem('content'); } }
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.
setInterval(function() { for (var i = 0; i < editables.length; i++) { localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML); } }, 5000);
You can also save the changes on every keydown
event.
document.addEventListener('keydown', function(e) { for (var i = 0; i < editables.length; i++) { localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML); } });
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.
<div id="toolbar"> <button id="addh1">H1</button> <button id="addh2">H2</button> </div>
Now, lets make that actually do something. We need to add a click
event that inserts a heading into the content block.
document.querySelector("#addh1").addEventListener("click", function (e) { const text = prompt( "What text do you want the heading to have?", "Heading" ); editables[2].innerHTML = editables[2].innerHTML + `<h1>${text}</h1>`; });
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.
document.querySelector("#addh2").addEventListener("click", function (e) { const text = prompt( "What text do you want the heading to have?", "Heading" ); editables[2].innerHTML = editables[2].innerHTML + `<h2>${text}</h2>`; });
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.
body { font-family: Arial; font-size: 1.3em; line-height: 1.6em; } .headline { font-size: 2em; text-align: center; } #wrapper { width: 600px; background: #fff; padding: 1em; margin: 1em auto; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3); border-radius: 3px; } button { border: none; padding: 0.8em; background: #f96; border-radius: 3px; color: white; font-weight: bold; margin: 0 0 1em; } button:hover, button:focus { cursor: pointer; outline: none; } #editor { padding: 1em; background: #e6e6e6; border-radius: 3px; }
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.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
Monty Shokeen | Sciencx (2016-01-06T20:33:06+00:00) Create an Inline Text Editor With the contentEditable Attribute. Retrieved from https://www.scien.cx/2016/01/06/create-an-inline-text-editor-with-the-contenteditable-attribute/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.