I want to run a function when a user edits the content of a div
with contenteditable
attribute. What's the equivalent of an onchange
event?
I'm using jQuery so any solutions that uses jQuery is preferred. Thanks!
I want to run a function when a user edits the content of a div
with contenteditable
attribute. What's the equivalent of an onchange
event?
I'm using jQuery so any solutions that uses jQuery is preferred. Thanks!
Here is a more efficient version which uses
on
for all contenteditables. It's based off the top answers here.The project is here: https://github.com/balupton/html5edit
Here is the solution I ended up using and works fabulously. I use $(this).text() instead because I am just using a one line div that is content editable. But you may also use .html() this way you dont have to worry about the scope of a global/non-global variable and the before is actually attached to the editor div.
Two options:
1) For modern (evergreen) browsers: The "input" event would act as an alternative "change" event.
https://developer.mozilla.org/en-US/docs/Web/Events/input
or
or (with jQuery)
2) To account for IE11 and modern (evergreen) browsers: This watches for element changes and their contents inside the div.
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
I have modified lawwantsin 's answer like so and this works for me. I use the keyup event instead of keypress which works great.
Based on @balupton's answer:
Consider using MutationObserver. These observers are designed to react to changes in the DOM, and as a performant replacement to Mutation Events.
Pros:
Cons:
Learn more: