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!
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!
Check this idea out. http://pastie.org/1096892
I think it's close. HTML 5 really needs to add the change event to the spec. The only problem is that the callback function evaluates if (before == $(this).html()) before the content is actually updated in $(this).html(). setTimeout don't work, and it's sad. Let me know what you think.
Here's what worked for me:
To avoid timers and "save" buttons, you may use blur event wich fires when the element loses focus. but to be sure that the element was actually changed (not just focused and defocused), its content should be compared against its last version. or use keydown event to set some "dirty" flag on this element.
I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that
keydown
andkeypress
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 thecut
copy
andpaste
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 forcontenteditable
elements in current Mozilla (from Firefox 14) and WebKit/Blink browsers, but not IE.Demo:
Demo: http://jsfiddle.net/ch6yn/2691/
The onchange event doesn't fires when an element with the contentEditable attribute is changed, a suggested approach could be to add a button, to "save" the edition.
Check this plugin which handles the issue in that way:
I built a jQuery plugin to do this.
You can simply call
$('.wysiwyg').wysiwygEvt();
You can also remove / add events if you wish