onChange event with contenteditable [duplicate]
Code like:
...text <span contenteditable="true" onChange="someFunction()">blah blah</span> text...
The onChange event doesn't work. (at least in FireFox)
I don't want to use textarea/input tags, because there must be available to change only particular words in text, and must be displayed inline (not block).
Is there any way how to do that ?
Not really. Recent WebKit browsers support the HTML5 input
event on contenteditable
elements, which is ideal, but not supported in other browsers (UPDATE 31 December 2012: Firefox supports this as of version 14). Otherwise you may be able to get by with DOM mutation events DOMNodeInserted
, DOMNodeRemoved
and DOMCharacterDataModified
, but these have two disadvantages: firstly, they are not supported in IE < 9 or any version of Opera for contenteditable
elements, and secondly, a new spec with replacement events is in the works, meaning they are likely to be replaced in future browsers.
Live example: http://jsfiddle.net/MBags/
Or you could go lower level and handle key, mouse and clipboard events (cut
and paste
), which will work in all major browsers but will mean you'll need to check whether the editable content has changed each time such an event fires, which will get laggy and harm user experience for large pieces of content.
I built a jQuery plugin to do this.
(function ($) {
$.fn.wysiwygEvt = function () {
return this.each(function () {
var $this = $(this);
var htmlOld = $this.html();
$this.bind('blur keyup paste copy cut mouseup', function () {
var htmlNew = $this.html();
if (htmlOld !== htmlNew) {
$this.trigger('change');
htmlOld = htmlNew;
}
})
})
}
})(jQuery);
You can simply call $('.wysiwyg').wysiwygEvt();
You can also remove / add events if you wish