Categories
JavaScript Answers

How to Listen for Text Highlight in an HTML Element with JavaScript?

Spread the love

To listen for text highlight in an HTML element with JavaScript, we can listen to the selectionchange event.

For instance, if we have the following div:

<div>  
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus aliquam iaculis. Pellentesque interdum elit sapien, quis interdum enim laoreet sed. Mauris varius magna ac dapibus molestie. Sed porttitor sapien eget ipsum aliquet, lacinia venenatis lacus finibus. Phasellus in nibh mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed placerat tristique augue, id lacinia massa iaculis eu. Donec sed vestibulum odio. Fusce sit amet congue odio, eu consequat neque. Sed sed mauris id sem malesuada blandit eu at quam.  
</div>

Then we can write:

document.addEventListener("selectionchange", event => {  
  const selection = document.getSelection ? document.getSelection().toString() : document.selection.createRange().toString();  
  console.log(selection);  
})

to listen to the selectionchange event on document , which means we pick up all text selection changes on the page.

In the event handler, we call getSelection to get the text selection if it exists.

Otherwise, we call document.selection.createRange().toString() to get the text selection.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.