Skip to content

Instantly share code, notes, and snippets.

@prettycode
Created January 2, 2011 21:42
Show Gist options
  • Save prettycode/762848 to your computer and use it in GitHub Desktop.
Save prettycode/762848 to your computer and use it in GitHub Desktop.
// Working example: http://www.jsfiddle.net/mUrVB/22/
(function($) {
$.fn.selection = function() {
var start = this[0].selectionStart,
end = this[0].selectionEnd;
if (start === end) {
return null;
}
return {
start: start,
end: end,
equals: function(selection) {
return selection && selection.start === start && selection.end === end;
}
};
};
$.fn.monitorSelection = function() {
return self = this.bind("keyup mousemove keydown mouseup click", function(event) {
var lastSelection = self.data("lastSelection");
var currentSelection = self.selection();
// If there's a selection and there wasn't one or it has changed
if (currentSelection && (!lastSelection || !currentSelection.equals(lastSelection))) {
event.type = "onSelected";
self.trigger(event, [currentSelection.start, currentSelection.end]);
}
// If there was a selection and now there's not
else if (!currentSelection && lastSelection ) {
event.type = "onDeselected";
self.trigger(event);
}
self.data("lastSelection", currentSelection);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment