JSFiddle - React, Tailwind, and code Playground
by timdown
HTML
<input type="button" onmousedown="showSelected()" value="Show selected">
<p>The quick brown fox jumped over the fence.</p>
<p>A paragraph containing some more text</p>
JavaScript
function getSelectedText() {
var selectedText = "", containerText = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0);
selectedText = range.toString();
var container = range.commonAncestorContainer;
if (container.nodeType == 3) {
container = container.parentNode;
}
containerText = container.textContent;
}
} else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
var textRange = document.selection.createRange();
selectedText = textRange.text;
containerText = textRange.parentElement().innerText;
}
return {
selectedText: selectedText,
containerText: containerText
};
}
function showSelected() {
var sel = getSelectedText();
alert("Selected: '" + sel.selectedText + "', container text: '" + sel.containerText + "'");
}