Select Events (selectstart, selection change)

Devtool Chrome Event Listener

About

This page is about the events that are fired when a selection of text occurs

List

select

The select event 1) 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:

The select event is fired on the mouseup after the selection of text.

Demo:

<textarea cols=50 rows=5>
Select this text, one letter at a time 
and see that the element is fired on mouseup
</textarea>
<p>Select this text in a p element and see that the <mark>select</mark> event is not fired</p>
document.addEventListener('select',()=>{
  console.log('The select event has fired')
})

selectstart

See the dedicated page: What is the selectstart DOM event with examples and howto's in Javascript?

selectionchange

When the selection object has changed, the selectionchange 2) is fired.

Demo:

  • The text to select
<ul>
  <li id="node-1">Select this text, one letter at a time to see the selectionchange event usage</li>
  <li id="node-2">Click on it and see the event firing</li>
  <li id="node-3">Select multiple line and see the offset</li>
</ul>
  • The javascript that logs information when the event fires.
document.addEventListener('selectionchange',(event)=>{
  let selection = document.getSelection();
  let range = `(${selection.anchorNode.parentNode?.id}, offset ${selection.anchorOffset}) to (${selection.focusNode.parentNode?.id}, offset ${selection.focusOffset})`;
  let collapsed = selection.isCollapsed ? 'Collapsed' : 'Not Collapsed';
  switch (selection.type) {
     case 'Caret':
     case 'Range':
     case 'None':
       break;
     default:
       debugger;
  }
  console.log(`Selection has changed: Type: ${selection.type}, ${range}, ${collapsed}`)
  console.log(`  You selected ${selection.toString()}`)
})
  • Result:





Discover More
Browser
How to select text dynamically in a Browser with Javascript? The window Selection Object explained

How to manipulate the selection made by a mouse or with the keyboard in a browser
Devtool Chrome Event Listener
What is the selectstart DOM event with examples and howto's in Javascript?

selectstart is a selection event that occurs when the user agent (the browser used by the user mostly) is to associate a new range to a selection object Note that when the user clicks on: a text,...



Share this page:
Follow us:
Task Runner