Skip to content
Examples to demonstrate use of the Selection API.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
README.md adding setBaseAndExtent() example Mar 1, 2017
index.html adding keyquotes example Jan 19, 2017
keyquote.css fixing css issue Feb 24, 2017
keyquote.js adding keyquotes example Jan 19, 2017
setBaseAndExtent.html adding setBaseAndExtent() example Mar 1, 2017

README.md

selection-api-examples

Examples to demonstrate use of the Selection API.

Key quote generator (see it running live)

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 document.getSelection() method.

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.

setBaseAndExtent() example (see it running live)

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 anchorOffset and 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.

You can’t perform that action at this time.