Using Contenteditable Attribute

With the help of contenteditable attribute, we can make regular HTML elements editable like an input field.

The original goal of the attribute was to make more modern and better WYSIWYG editors where we don’t need an iframe.

Possible values of the attribute:

  • contenteditable or contenteditable=”true” – turn on the item’s editing,
  • contenteditable=”false” – turn off the item’s editing,
  • ontenteditable=”inherit” – the item is editable if the parent item is.

See the Pen Contenteditable tulajdonság – 01 by Adam Laki (@adamlaki) on CodePen.

Event Watch

The elements with contenteditable attribute behave like a regular input field so you can also catch the similar events as you do with the form data.

You can use the followings:

  • focus – triggered when you click on an editable element
  • input – triggered when the editable element’s content change
  • keypress – triggered when you typing into the element
  • blur – triggered when you click outside of the element

To watch change one of the best events is the input like this:

document.getElementById('editable-text').addEventListener('input', function() {
    console.log('Változott a tartalmunk!');
});

Language check

When you use this attribute your newly editable field will be spell checked which can be annoying in some cases. You can simply turn it off with the following snippet:

<div contenteditable="true" spellcheck="false">Az elem tartalma.</div>

You can also use the spellcheck attribute on input and textarea fields.

Cursor position

To make an element editable with a click or some other interaction then it is possible that you need to set the position to the end of the element’s end.

var node = document.querySelector("div"),
    textNode = node.firstChild,
    caret = textNode.length,
    range = document.createRange(),
    sel = window.getSelection();

node.focus();

range.setStart(textNode, caret);
range.setEnd(textNode, caret);

sel.removeAllRanges();
sel.addRange(range);

Example

In this example, you can edit the name and the description after you click on the edit button. These fields are an
and a tag.

See the Pen Editable User Card by Adam Laki (@adamlaki) on CodePen.