Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

contenteditable change events

I want to run a function when a user edits the content of a div with contenteditable attribute. What's the equivalent of an onchange event?

I'm using jQuery so any solutions that uses jQuery is preferred. Thanks!

like image 525
Jourkey Avatar asked Sep 07 '09 23:09

Jourkey


People also ask

How do I save a Contenteditable change?

You can use localStorage to save data. The trigger can be when contentEditable gets disabled. Save the content into localStorage and upon page load, restore the localStorage value (if there is one), or load the default content if not.

What is false about Contenteditable attribute?

contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.

What does Contenteditable mean?

The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.

What does Contenteditable attribute do?

The contenteditable attribute specifies whether the content of an element is editable or not.


2 Answers

I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that keydown and keypress events are fired before the content itself is changed. This won't cover every possible means of changing the content: the user can also use cut, copy and paste from the Edit or context browser menus, so you may want to handle the cut copy and paste events too. Also, the user can drop text or other content, so there are more events there (mouseup, for example). You may want to poll the element's contents as a fallback.

UPDATE 29 October 2014

The HTML5 input event is the answer in the long term. At the time of writing, it is supported for contenteditable elements in current Mozilla (from Firefox 14) and WebKit/Blink browsers, but not IE.

Demo:

document.getElementById("editor").addEventListener("input", function() {      console.log("input event fired");  }, false);
<div contenteditable="true" id="editor">Please type something in here</div>

Demo: http://jsfiddle.net/ch6yn/2691/

like image 186
Tim Down Avatar answered Sep 21 '22 18:09

Tim Down


Here is a more efficient version which uses on for all contenteditables. It's based off the top answers here.

$('body').on('focus', '[contenteditable]', function() {     const $this = $(this);     $this.data('before', $this.html()); }).on('blur keyup paste input', '[contenteditable]', function() {     const $this = $(this);     if ($this.data('before') !== $this.html()) {         $this.data('before', $this.html());         $this.trigger('change');     } }); 

The project is here: https://github.com/balupton/html5edit

like image 37
balupton Avatar answered Sep 23 '22 18:09

balupton