Last Updated: March 10, 2018
·
50.36K
· conradgray

Listen to changes on a contenteditable element

Here is the problem I have to solve today. We have an element with contenteditable attribute, so the user can edit it. Now, how to know when user changed it?

Let's make an contenteditable element:

<div id="text" contenteditable>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec at arcu ac dui eleifend suscipit a ut est. Ut iaculis ut massa non accumsan. Quisque hendrerit nisl at egestas cursus.
</div>

Nothing fancy, just a simple div.

Since contenteditable elements doesn't have change event my first idea was to use key events. It's a good idea, but it wasn't good for me. After quick research I found solution - input event.

input event is fired when something in an input or textarea element has changes and it's also fired when something has changed in elements with contenteditable attribute. Perfect!

Here's an example of function that is fired when content of contenteditable has changed:

var editable = document.getElementById('text');
editable.addEventListener('input', function() {
    console.log('Hey, somebody changed something in my text!');
});

You can read more about input event on MDN. Currently this feature is available only on Chrome, Firefox 14+ and Safari.