Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window
and document
objects.
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
If you're interested in an implementation that will also deal with selections in <textarea>
and texty <input>
elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.
function getSelectionText() {_x000D_
var text = "";_x000D_
var activeEl = document.activeElement;_x000D_
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;_x000D_
if (_x000D_
(activeElTagName == "textarea") || (activeElTagName == "input" &&_x000D_
/^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&_x000D_
(typeof activeEl.selectionStart == "number")_x000D_
) {_x000D_
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);_x000D_
} else if (window.getSelection) {_x000D_
text = window.getSelection().toString();_x000D_
}_x000D_
return text;_x000D_
}_x000D_
_x000D_
document.onmouseup = document.onkeyup = document.onselectionchange = function() {_x000D_
document.getElementById("sel").value = getSelectionText();_x000D_
};
_x000D_
Selection:_x000D_
<br>_x000D_
<textarea id="sel" rows="3" cols="50"></textarea>_x000D_
<p>Please select some text.</p>_x000D_
<input value="Some text in a text input">_x000D_
<br>_x000D_
<input type="search" value="Some text in a search input">_x000D_
<br>_x000D_
<input type="tel" value="4872349749823">_x000D_
<br>_x000D_
<textarea>Some text in a textarea</textarea>
_x000D_