Browser - Selection (window)

1 - About

The selection feature is based on :

3 - Example

3.1 - Expanding selection with selectstart

This example will demonstrate how to force a selection of whole section when the user try to select only one word of the section.


<section id="parent">
   <h1>You can select only the whole section</h1>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
</section>

  • The callback function that is fired with the event selectstart that:
    • define a range being the start of the h1 and the last character of the p text node
    • and update the selection object

let handleExpandSelectionToContainer = function(event) {
    // Set the range
    var range = document.createRange();
    var parent = this; // the section
    var h1TextNode = parent.firstElementChild.firstChild;
    var pTextNode = parent.lastElementChild.firstChild;
    range.setStart(h1TextNode, 0);
    range.setEnd(pTextNode, pTextNode.length);
    // Set the selection
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
    // prevent
    event.preventDefault();
}

  • This code attach the callback function to the selectstart event.

var parent = document.getElementById("parent");
parent.addEventListener('selectstart', handleExpandSelectionToContainer );

  • Result: Try to select only one word. You will only select the whole text

4 - Event

4.1 - select

The select event occurs when a user selects some text in form controls when their text selection is adjusted (whether by an API or by the user). In HTML5, select events occurs only on form controls:

Ref

4.2 - selectstart

The selectstart event occurs when the user agent is about to associate a new range to a selection object.

Ref

4.3 - selectionchange

When the selection object has changed, the selectionchange is fired. Ref

5 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap