[javascript] onChange event with contenteditable

1 Answers

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) {
                    htmlOld = htmlNew;

You can simply call $('.wysiwyg').wysiwygEvt();

You can also remove / add events if you wish


This question already has an answer here:

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 ?

Because non-input elements don't have traditional input-like events, you have to sort of mash something together yourself. To that end:

var editable = document.querySelectorAll('div[contentEditable]');

for (var i=0, len = editable.length; i<len; i++){

    editable[i].onblur = function(){
        if (this.innerHTML == this.getAttribute('data-orig')) {
            // no change
        else {
            // change has happened, store new value

JS Fiddle demo.

Though as noted by Tim Down this shouldn't be necessary for too much longer, with the obvious exception of supporting older browsers.