Skip to content

Instantly share code, notes, and snippets.

@zapthedingbat
Created March 19, 2014 10:21
Show Gist options
  • Save zapthedingbat/9639013 to your computer and use it in GitHub Desktop.
Save zapthedingbat/9639013 to your computer and use it in GitHub Desktop.
jQuery Valuechange event and handler
/* Valuechange event and handler
* See: http://learn.jquery.com/events/event-extensions/
*/
(function($) {
var name = "valuechange";
$.event.special[name] = {
// Event is bound
add: function(handleObj) {
var eventNames = ["input", "propertychange", "drop", "paste", "keyup"],
namespace = "." + name + (handleObj.namespace ? '.' + handleObj.namespace : ''),
element = $(this);
var events = $.map(eventNames, function(eventName) {
return eventName + namespace;
}).join(" ");
// bind events raised by value changing
element.on(events, handleObj.selector, function(event) {
var
value = event.target.value,
data = jQuery.data(event.target),
previousValue = (data.previousValue || "");
if (previousValue !== value) {
event.type = handleObj.origType;
$.event.dispatch.apply(this, arguments);
event.type = handleObj.type;
data.previousValue = value;
}
});
},
// Event is unbound
remove: function(handleObj) {
// unbind events raised by value changing
var namespace = "." + name + (handleObj.namespace ? '.' + handleObj.namespace : ''),
element = $(this);
element.off(namespace, handleObj.selector);
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment