Reputation: 3617
Unfortunately, the "change" event for a <textarea> only fires when the element looses focus.
I'd like to fire an alert() when the content of it actually changes, while the element is still focussed.
Here's what I've got:
var $editor = $("#editor")
.keydown(function () {
$editor.data("before-keydown", $editor.val());
})
.keyup(function () {
if ($editor.data("before-keydown") !== $editor.val()) {
alert("content has changed");
}
});
Is there any better way to determine when the contents of the <textarea> change?
Upvotes: 2
Views: 1159
Reputation: 344517
You should be using the HTML5 oninput
event, it trumps key events for capturing text input and most browsers have supported it for a while now. The exception is Internet Explorer, although it's in the latest Internet Explorer 9 preview. Internet Explorer can emulate this event, however, using its own proprietary event onpropertychange
, which will fire every time the value
property changes.
oninput
will fire for all forms of input, such as cut, paste, spelling auto-correct, drag and drop, etc. Since you're using jQuery, you could take a look at my plugin which handles the differences and normalizes the event as much as possible for Internet Explorer and older browsers. This would make your code look something like this:
var $editor = $("#editor").input(function() {
alert("content has changed");
});
Working demo: http://jsfiddle.net/9YcPu/
nb: it's also worth mentioning that oninput
doesn't fire if the value doesn't change, for instance if you highlight a section of text and copy/paste the same selection over the top so that the text stays the same.
Upvotes: 5