JavaScript: How to Capture Highlighted Text

Programming Books Setting or Sitting on a Shelf by a Cactus

I’ve been noticing a trend on the web lately. When you double click or highlight text on some websites a fancy little box pops up right above that section. It gives you options like: Tweeting, Editing, Sharing or really anything the website could want. The image below has an example of what I’m talking about.

Example of Highlighted Text Popup Dialog

 

I had to find out for myself how they were doing it. So, here’s what I found…

**I checked that this worked on pretty much every browser, and it did. It even worked on the infamous Edge browser.

 

All you need to do to get this to work on your site is to use the following line of code:

window.getSelection().toString();

 

Now that you’ve seen the function by itself I’ll show you how you might implement this on a real website. Just use JQuery to make your life a lot easier, then drop in some code like the following:

$(document).on("click", function() {
    if (window.getSelection().toString() !== "") {
        alert(window.getSelection().toString());
    }
});

 

In the above code I’ve used the on click event handler. I then check if the window selection contained an empty string or not, and if not then create a pop-up to show what was selected.

Here’s a helpful link to Stack Overflow with more details (and plenty of bickering) on how you could do this differently.


Photo courtesy of: Greg Rakozy

Leave a Reply

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