trigger an event when contenteditable is changed

2019-01-06 17:47发布

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

12条回答
狗以群分
2楼-- · 2019-01-06 18:07

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);
        }
    });
});
查看更多
在下西门庆
3楼-- · 2019-01-06 18:08

Yet another version in jquery. View in jsFiddle here.

var $editableContent = $("#mycontent");

//  Implement on text change
$editableContent.on("focus", function(event) {$(this).data("currentText", $(this).text());});

$editableContent.on("blur", function (event) {
        if ($(this).text() != $(this).data("currentText")) {
                $(this).trigger('change');}});


//  Wire onchange event
$editableContent.on("change", function(){alert("Text changed to: " + $(this).text())});
查看更多
欢心
4楼-- · 2019-01-06 18:10

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

查看更多
看我几分像从前
5楼-- · 2019-01-06 18:12

Another solution which is slightly modified version of previous ones but it may be more comfortable to use for some of you.

Idea is to save origin value and compare it with current value in 'blur' event. I save origin value as attribute of editable div tag (instead of creating variable for origin value). Using attribute as container for origin value is more comfortable when one has a huge number of editable divs in table (as cells). So it is easy to get origin value since you don't need to create many variables.

See my complete example code:

editable div

<td><div contenteditable="true" class="cell" origin="originValue">originValue</div></td>

detecting changes in blur

var cells = $("#table").find('td>div[contenteditable=true]');

cells.each(function () {    

        $(this).blur(function() {

                    if ($(this).text() != $(this).attr("origin")) {
                        console.log('changed');
                    }
        });    
});
查看更多
够拽才男人
6楼-- · 2019-01-06 18:12

function myFunction(){
  alert('Handler for .change() called.');
}
<div class="changeable" contenteditable="true" onfocusout="myFunction()" > Click this div to edit it <div>

查看更多
唯我独甜
7楼-- · 2019-01-06 18:13

What you have to do is make a conjunction of blur and DOMSubtreeModified events on your contenteditable elements.

var contentEdited = false;

function fn($el) {
  if (contentEdited) {
    var text = $el[0].innerText.trim();
    console.log(text);
    contentEdited = false;
  }
}
$("div.editable").on("blur", function() {
  fn($(this));
}).on("DOMSubtreeModified", function() {
  contentEdited = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

查看更多
登录 后发表回答