Categories
JavaScript

JavaScript Events Handlers- onreadystatechange and onselectionchange

Spread the love

In JavaScript, events are actions that happen in an app. They’re triggered by various things like inputs being entered, forms being submitted, and changes in an element like resizing, or errors that happen when an app is running, etc. We can assign an event handler to handle these events.

Events that happen to DOM elements can be handled by assigning an event handler to properties of the DOM object for the corresponding events.

In this article, we will look at the onreadystatechange and the onselectionchange event handlers.

window.document.onreadystatechange

The onreadystatechange lets us attach an event handler to handle the readystatechange event. The readyState is changed as our page loads.

The event will be trigger when the document.readyState changes values, which can be one of 3 values, which is loading , which means that the document is loading, interactive , which means that the document has finished loading and the document has been parsed but sub-resources like images, stylesheets and frames are still loading, or complete , which means that the document and sub-resources have loaded.

For example, we can write the code to get the readyState of document as the page is loading:

document.onreadystatechange = () => {  
  console.log(document.readyState);  
};

If we run the code above, we should get something like:

interactive  
complete

from the console.log output.

We can look at the change of the readyState as the page loads with the code above. To look at it more slowly, we can go to the Network tab of Chrome and change the speed of that the page loads with the drop-down on the top of the tab. We can choose Fast 3G, Slow 3G, or choose ‘Add…’ to set our own speed.

window.document.onselectionchange

The onselectionchange property let us attach an event handler function to process the selectionchange event. The selectionchange event is fired when the current text selection on a document is changed. For example, we can use it like in the following code:

document.onselectionchange = () => {  
  console.log(document.getSelection());  
}

With the code above, we’re logging the Selection object, which represents the text that was selected by the user or the current position of the caret.

A user may make the selection from left to right or right to left. The anchor is where the user starts the selection and the focus is where the user ends the selection.

If the mouse is used for the selection then the anchor is placed where we place the mouse button and the focus is placed where we release the mouse button. The Selection object has the following value properties:

  • anchorNode — is a read-only that returns the Node in which the selection begins. It can return null if selection never existed in the document, for example, a page that was never clicked on will have no selection.
  • anchorOffset — is a read-only that returns a number representing the offset of the selection’s anchorNode within the anchor. If anchorNode is a text node, this is the number of characters within anchor preceding the anchor. If anchorNode is an element, this is the number of child nodes of the anchor preceding the anchor. The anchorNode property is a read-only property that has the Node is which the selection begins. It’ll have the data , textContent , and wholeText properties to get the data DOM Node that’s at the start of the selection.
  • focusNode — is a read-only that returns the node in which the selection ends. It can return null if selection never existed in the document, for example, a page that was never clicked on. It’ll have the data , textContent , and wholeText properties to get the data DOM Node that’s at the end of the selection.
  • focusOffset — is a read-only that returns a number representing the offset of the selection’s anchor within the focus node. If the focus node is a text node, this is the number of characters within the focus node preceding the focus. If focus node is an element, this is the number of child nodes of the focus node preceding the focus.
  • isCollapsed — is a read-only that returns a boolean that indicates whether the selection’s start and endpoints are in the same position.
  • rangeCount — is a read-only that returns the number of ranges in the selection.
  • type — is a read-only that returns a string describing the type of the current selection.

Also, it has a toString method that’ll get us the actual selected text. For example, we can use it below like in the code below:

document.onselectionchange = () => {  
  console.log(document.getSelection().toString());  
}

Then if we have the following HTML code:

<p>  
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque fermentum erat viverra odio condimentum, vitae feugiat ex condimentum. Maecenas convallis tempus nisl consequat mollis. Nullam tempus ultrices est id accumsan. Duis in dignissim magna. Sed rutrum ac metus ac faucibus. Proin ut ex felis. Donec malesuada eget neque a egestas. Donec vitae aliquet tellus. Suspendisse in egestas nisi. In consequat metus id enim bibendum faucibus. Praesent hendrerit, leo vitae sollicitudin sollicitudin, tellus ante ornare est, nec laoreet augue sem et orci. Etiam tempor pretium faucibus. Etiam eros mauris, hendrerit sed molestie a, eleifend sed eros. Etiam efficitur congue euismod.</p><p>  
  Quisque viverra nibh a ornare fermentum. In viverra, orci sed mattis sodales, nisl eros fermentum lectus, id lobortis ligula diam eu sem. Nulla in tincidunt enim. Donec suscipit tortor ac aliquet pharetra. Donec lobortis nibh in turpis dignissim dapibus. Nunc eu erat quis dui fermentum convallis. Fusce posuere, augue vitae mattis viverra, est velit finibus tellus, non dictum tortor dolor sit amet felis. Aliquam auctor risus urna, non posuere magna dapibus a. Vivamus iaculis lorem massa, eget mollis libero consectetur et. Integer iaculis lorem eget turpis accumsan, nec vulputate sapien accumsan. Donec facilisis arcu nec nisi posuere finibus vel non augue. Donec tempor tortor ac mauris efficitur, nec sollicitudin nisl commodo. Proin tincidunt odio ac turpis bibendum, sed aliquet metus fermentum. In hac habitasse platea dictumst.</p>

We get something like the following logged with the event handler:

us nisl consequat mollis. Nullam tempu

The onreadystatechange gets us the state of the page when it’s loading. It’s handy if we want to do something when the page is loading.

The onselectionchange event handlers let us process the selectchange event, which is triggered when users make selections on the page by highlighting content.

We can get the anchor and focus nodes for the selection inside the event handler by using the document.getSelection() method, and we can get the selected text by calling the toString() method on document.getSelection() .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *