

And when the user selects that text, our selection menu will prompt the user to tweet it. We’ll add the selection menu control to the page when user selects text.
Anything inside a tag is not rendered on the page until it’s later added to the page with JavaScript. In case that not any text is selected, those values (start and end) will be the same, which means that they're equivalent to the position of the cursor in the element. The inside it is our selection menu control.These values (start and end) provide always an integer value with the index of the selected text within a textarea or text input. A Selection object represents the range of text selected by the user or the current position of the caret. This way we can place the selection menu exactly above the selected text and get access to the selected text itself. Inside the function, we get the selection and the selected string using document.getSelection ().

Next, we write the handler function for the onpointerup event of the element carrying the sample text.
The API gives us access to the space and content of the selected area on a webpage. Print part of a webpage Click and drag over a section of text or images to select the part of the website you want to print. In this code, we first get a copy of the selection menu control inside , then assign it to the control variable.Although you won't get a property named " cursorPosition" or " caretPosition", you can deduct this value from the selectionStart property from the element which is basically the same. Let’s see how we can create a selection menu like this using JavaScript’s Selection API.
Related objects You can call Document.getSelection (), which works identically to Window.getSelection (). The inside it is our selection menu control.selectedText is a string (Selected text). Retrieve the position of the cursor (caret) within a textarea is easier than you think. To use a Selection object as a string, call its toString () method directly: const selectedText selObj.toString() selObj is a Selection object.
