trigger an event when contenteditable is changed

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.');
});

Solution 1:

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/

Solution 2:

You can simply use focus/blur event with data() function of jQuery :

// Find all editable content.
$('[contenteditable=true]')
    // When you click on item, record into data("initialText") content of this item.
    .focus(function() {
        $(this).data("initialText", $(this).html());
    });
    // When you leave an item...
    .blur(function() {
        // ...if content is different...
        if ($(this).data("initialText") !== $(this).html()) {
            // ... do something.
            console.log('New data when content change.');
            console.log($(this).html());
        }
    });
});

UPDATE: With Vanilla JS

// Find all editable content.
var contents = document.querySelectorAll("[contenteditable=true]");
[].forEach.call(contents, function (content) {
    // When you click on item, record into `data-initial-text` content of this item.
    content.addEventListener("focus", function () {
        content.setAttribute("data-initial-text", content.innerHTML);
    });
    // When you leave an item...
    content.addEventListener("blur", function () {
        // ...if content is different...
        if (content.getAttribute("data-initial-text") !== content.innerHTML) {
            // ... do something.
            console.log("New data when content change.");
            console.log(content.innerHTML);
        }
    });
});

Solution 3:

the best solution to this currently is the HTML5 input event

<div contenteditable="true" id="content"></div>

in your jquery.

$('#content').on('input', (e) => {
    // your code here
    alert('changed')
});

Solution 4:

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')
                }
            })
        })
    }
})(jQuery);

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

You can also remove / add events if you wish