Examples to demonstrate use of the Selection API.
This example contains a complete text on the right, and a list on the left, which starts empty.
When you select part of the text in the full quote, the
onselectionchanged event handler fires, which causes the current selection to be saved in a variable called
selection via the
When the "Create quote from selection" button is pressed, the current selection is converted to a text string using
selection.toString(). This string is then placed as the text content of a new list item, and the list item is appended to the list.
When the "Copy key quotes" is pressed, the entire contents of the list is added to the selection using
selection.selectAllChildren(quoteList);. We then copy the selection to the OS clipboard using
document.execCommand('copy');, and the text can now be copied anywhere you wish.
This example is know to work in Firefox, Chrome, Safari, and Edge; it has not been optimized for mobile.
In this example, we have two paragraphs containing
spans, each one containing a single word. The first one is set as the
anchorNode and the second is set as the
focusNode. We also have an additional paragraph that sits in between the two nodes.
Next, we have two form
inputs that allow you to set the
focusOffset — they both have a default value of 0.
We also have a
button that when pressed invokes a function that runs the
setBaseAndExtent() method with the specified offsets, and copies the selection into the output paragraph at the very bottom of the HTML.