Skip to content

Instantly share code, notes, and snippets.

@nwinkler
Last active August 29, 2015 14:03
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 nwinkler/5110fc7f1ec6caaeea27 to your computer and use it in GitHub Desktop.
Save nwinkler/5110fc7f1ec6caaeea27 to your computer and use it in GitHub Desktop.
Select text range in browser (outside of input fields)
/**
* From http://stackoverflow.com/a/987376/1228454
*
* Cross-browser function for selecting text ranges.
*
* @param element A jQuery element that has the text.
*/
function selectText(element) {
var doc = document,
range, selection;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(element[0]);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(element[0]);
selection.removeAllRanges();
selection.addRange(range);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment