Get the Highlighted/Selected Text
Is it possible to obtain text highlighted or selected by a user within a website using jQuery?
Answer:
Getting the user-selected text is straightforward. Using jQuery offers no advantages because it can be accomplished using the window and document objects.
function getSelectionText() { let text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }
Alternatively, if you wish to consider selections in
function getSelectionText() { let text = ""; const activeEl = document.activeElement; const activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null; if ( (activeElTagName == "textarea") || (activeElTagName == "input" && /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) && (typeof activeEl.selectionStart == "number") ) { text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd); } else if (window.getSelection) { text = window.getSelection().toString(); } return text; } document.onmouseup = document.onkeyup = document.onselectionchange = function() { document.getElementById("sel").value = getSelectionText(); };
The above is the detailed content of How Can I Get User-Selected Text from a Website Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!