javascript working - onChange event with contenteditable




not field (5)

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 ?


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) {
                    $this.trigger('change');
                    htmlOld = htmlNew;
                }
            })
        })
    }
})(jQuery);

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

You can also remove / add events if you wish


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.


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].setAttribute('data-orig',editable[i].innerHTML);

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

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.


The function that I wrote:
One call of this function fixes all ContentEditable elements in the page.

function fix_onChange_editable_elements()
{
  var tags = document.querySelectorAll('[contenteditable=true][onChange]');//(requires FF 3.1+, Safari 3.1+, IE8+)
  for (var i=tags.length-1; i>=0; i--) if (typeof(tags[i].onblur)!='function')
  {
    tags[i].onfocus = function()
    {
      this.data_orig=this.innerHTML;
    };
    tags[i].onblur = function()
    {
      if (this.innerHTML != this.data_orig)
        this.onchange();
      delete this.data_orig;
    };
  }
}

In IE and Chrome, event is resolving to window.event. Firefox doesn't have this property and instead provides an event to an event handler function by passing it as a parameter. jQuery abstracts this difference for you by providing an event object parameter in all browsers:

$("<a />")
    .append("demo")
    .click(function (evt) { DemoFunc(evt, value.Id) });




javascript html5