trigger an event when contenteditable is changed

johnmosly picture johnmosly · Jun 6, 2011 · Viewed 54.4k times · Source

When a divs value is changed, how Can I trigger an event?

<div class="changeable" contenteditable="true"> Click this div to edit it <div>

So when its content changes I want to create an alert and/or do other things:

$('.changeable').text().change(function() {
  alert('Handler for .change() called.');
});

Answer

Niklas picture Niklas · Jun 6, 2011

Just store the contents to a variable and check if it is different after blur() event. If it is different, store the new contents.

var contents = $('.changeable').html();
$('.changeable').blur(function() {
    if (contents!=$(this).html()){
        alert('Handler for .change() called.');
        contents = $(this).html();
    }
});

example: http://jsfiddle.net/niklasvh/a4QNB/