Reputation: 1760
I want to be able to detect if something has changed in a div. I have two divs, one for a heading and one for a message, i could just use normal input methods like textarea and input of text but i want the look of the site to be sleek and would rather they look like normal web page elements till a user clicks on them (I am also using CKEditor to do inline text editing).
<h1 contenteditable="true" class="editable-header">A Heading</h1>
<div class="update-text" contenteditable="true">
A message
</div>
So i would like to be able to change the state of a button on when something has changed in one of those boxes using Jquery.
I have tried using
$(".editable-header").change( function(){
console.log("Something has changed!");
});
But this doesn't seem to fire, i also tried
$(".editable-header").on("change", function(){});
Change this be done with an editable div? If so, how?
Upvotes: 1
Views: 809
Reputation:
JavaScript
function OnEditableObjectChange(ClassName, Callback)
{
var interval = 0;
var elts = document.getElementsByClassName(ClassName);
for(var i = 0; i < elts.length; ++i)
{
elts[i].addEventListener("focus", function(){
var that = this;
interval = setInterval(function(){
Callback(that.innerHTML);
}, 16);
}, false);
elts[i].addEventListener("blur", function(){
clearInterval(interval);
}, false);
}
}
/* Exemple */
OnEditableObjectChange("editable-header", function(txt){
document.getElementsByClassName("update-text")[0].innerHTML = txt;
});
JsFiddle
Does it respond to your needs ? :)
(Sorry if my english is not really good, I'm french ^^)
Upvotes: 0
Reputation: 399
Use input
event for this.
$(".editable-header").on("input", function(){console.log('edited')});
Update
input
doesn't work in IE10-11, which is a reported bug.
On contrary, keyup
works in IE too.
$(".editable-header").keyup(callback);
function callback() {
console.log('edited');
}
Note: using both events at the same time will cause callback to be executed twice in FF and Chrome.
Upvotes: 1
Reputation: 12117
h1
is not input element so when the content change inside h1
at that time You need to attach event
, see sample code
<h1 contenteditable="true" class="editable-header">A Heading</h1>
<div class="update-text" contenteditable="true">
A message
</div>
<input type="button" value="Change title"/>
And jQuery code
$(".editable-header").change( function(){
alert("Something has changed!");
});
$("input[type=button]").on('click', function(){
$(".editable-header").text("Fooo").trigger("change");
//OR $(".editable-header").text("Fooo").change();
});
UPDATE on comment, if element
is contenteditable="true" then this code to work combine even change content by keyword or dynamically.
$(".editable-header").on('keyup change', function(){
alert("Something has changed!");
});
Upvotes: 2
Reputation: 1260
You can use blur event....but you need to check it's text really changed
$(".editable-header").on("blur", function(){};
Upvotes: 0