Skip to content

Instantly share code, notes, and snippets.

@nathanhammond
Forked from mkelly12/jquery.textchange.js
Created August 27, 2010 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanhammond/553602 to your computer and use it in GitHub Desktop.
Save nathanhammond/553602 to your computer and use it in GitHub Desktop.
Properly setup the event to account for initial content at the time of the first event binding. Reduce the delay to make it fire as quickly as possible. Remove two unused special events. Formatting.
/*!
* jQuery TextChange Plugin
* http://www.zurb.com/playground/jquery-text-change-custom-event
*
* Copyright 2010, ZURB
* Released under the MIT License
*/
(function ($) {
$.event.special.textchange = {
setup: function (data, namespaces) {
$this = $(this);
var current = $this[0].contentEditable === 'true' ? $this.html() : $this.val();
$this.bind('keyup.textchange keydown.textchange keypress.textchange', $.event.special.textchange.handler);
$this.bind('cut.textchange paste.textchange input.textchange', $.event.special.textchange.delayedHandler);
$this.data('lastValue', current);
},
teardown: function (namespaces) {
$(this).unbind('.textchange');
},
handler: function (event) {
$.event.special.textchange.triggerIfChanged($(this));
},
delayedHandler: function (event) {
var element = $(this);
setTimeout(function () {
$.event.special.textchange.triggerIfChanged(element);
}, 1);
},
triggerIfChanged: function (element) {
var current = element[0].contentEditable === 'true' ? element.html() : element.val();
if (current !== element.data('lastValue')) {
element.trigger('textchange', element.data('lastValue'));
element.data('lastValue', current);
}
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment