Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Set Window selection

Tags:

In JavaScript, there is a method window.getSelection(), that lets me get the current selection that the user has made.

Is there a corresponding function, something like window.setSelection(), that will let me set, or clear, the current selection?

like image 297
Richard J. Ross III Avatar asked May 31 '11 15:05

Richard J. Ross III


People also ask

How do you create a selection in Javascript?

The second API is very simple, as it works with text. Setting the selection: let selection = document. getSelection(); // directly: selection.

What is getSelection in Javascript?

getSelection() The Window. getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.

What is a selection anchor?

The anchor is where the user began the selection and the focus is where the user ends the selection.

How do you create an action for selected text with the selection API?

In this code, we first get a copy of the selection menu control inside <template> , then assign it to the control variable. Next, we write the handler function for the onpointerup event of the element carrying the sample text. Inside the function, we get the selection and the selected string using document.


2 Answers

Clearing the selection in all major browsers:

function clearSelection() {     if (window.getSelection) {         window.getSelection().removeAllRanges();     } else if (document.selection) {         document.selection.empty();     } } 

Selecting content requires use of DOM Range and Selection objects in most browsers and TextRange objects in IE < 9. Here's a simple cross-browser example that selects the contents of a particular element:

function selectElement(element) {     if (window.getSelection) {         var sel = window.getSelection();         sel.removeAllRanges();         var range = document.createRange();         range.selectNodeContents(element);         sel.addRange(range);     } else if (document.selection) {         var textRange = document.body.createTextRange();         textRange.moveToElementText(element);         textRange.select();     } } 
like image 164
Tim Down Avatar answered Sep 20 '22 00:09

Tim Down


Maybe this will do it:

window.selection.clear(); 

Crossbrowser version:

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(); } 
like image 29
stefgosselin Avatar answered Sep 22 '22 00:09

stefgosselin