Skip to content

Instantly share code, notes, and snippets.

@terryyounghk
Last active December 31, 2015 15:09
Show Gist options
  • Save terryyounghk/8005151 to your computer and use it in GitHub Desktop.
Save terryyounghk/8005151 to your computer and use it in GitHub Desktop.
This gist contains four small jQuery plugins, namely .selectText(), $.deselectText(), .disableSelection() and .enableSelection(). .disableSelection() and .enableSelection() has been deprecated since jQuery UI 1.9 - this gist brings back those two functionalities, without the jQuery UI dependency. .selectText() and $.deselectText() is not a new c…
/*jshint multistr: true */
(function ($) {
/**
* Selects text within the DOM element
*/
$.fn.selectText = function() {
var doc = document,
element = this[0],
range,
selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
return this;
};
/**
* Deselects any selected text on the screen
*/
$.deselectText = function () {
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
/**
* .disableSelection() is deprecated in jQuery 1.9
*
* This utility function mimics the original function
* to disable text selection within a DOM element.
*
* Note that this actually uses a CSS solution
*
* @returns this, for method-chaining
*/
$.fn.disableSelection = function () {
return this
.addClass('unselectable')
.attr('unselectable', 'on') // jQuery UI
.css('user-select', 'none') // standard
.on('selectstart', false); // IE9 or lower
};
/**
* The opposite of .disableSelection()
*
* @returns this, for method-chaining
*/
$.fn.enableSelection = function () {
return this
.removeClass('unselectable')
.removeAttr('unselectable') // jQuery UI
.css('user-select', 'text') // standard
.on('selectstart', true); // IE9 or lower
};
/**
* This injects a CSS rule to facilitate .disableSelection()
*/
$(document).ready(function () {
$('html > head').append(
'<style> \
.unselectable { \
-ms-user-select: none; /* IE 10+ */ \
-moz-user-select: -moz-none; \
-khtml-user-select: none; \
-webkit-tap-highlight-color: rgba(0,0,0,0); /* Disable tap highlighting */ \
-webkit-touch-callout: none; \
-webkit-user-select: none; \
user-select: none; \
} \
</style>'
);
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment