views:

1072

answers:

5

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

Thanks.

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

A: 

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:

CMS
+1  A: 

I'd suggest attaching listeners to key events fired by the editable element, thought you need to be aware that keydown and keypress events are fired before the content itself is changed, so you may need to do something timer-based.

Tim Down
I should also add that it's possible to change an editable element by using the browser's edit menu or context menu to cut, copy or paste content, so you'll need to handle `cut`, `copy` and `paste` events in browsers that support them (IE 5+, Firefox 3.0+, Safari 3+, Chrome)
Tim Down
+1  A: 

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.

joox
A: 

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.

A: 

I have modified lawwantsin 's answer like so and this works for me. I use the keyup event instead of keypress which works great.

$('#editor').live('focus', function() {
  before = $(this).html();
}).live('blur keyup paste', function() { 
  if (before != $(this).html()) { $(this).trigger('change'); }
});

$('#editor').live('change', function() {alert('changed')});
Dennkster