When a divs value is changed, how Can I trigger an event?
Click this div to edit it
-
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/
讨论(0)
-
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
讨论(0)
-
function myFunction(){
alert('Handler for .change() called.');
}
<div class="changeable" contenteditable="true" onfocusout="myFunction()" > Click this div to edit it <div>
讨论(0)
-
Here is a jquery-version:
function fix_contenteditableOnchange(obj)
{
div=$(obj);
var contents = div.html();
var onchange = div.attr('onchange');
div.blur(function() {
if (contents!=$(this).html()){
eval(onchange);
fix_contenteditableOnchange(obj);
}
});
}
Try this out.
讨论(0)
-
It's more simple to do it using EventListener (not a jQuery method):
document.getElementById("editor").addEventListener("input", function() {
alert("input event fired");
}, false);
讨论(0)
-
This is my approach...
$('.changeable').focusout(function() {
alert('Handler for .change() called.');
});
讨论(0)