JavaScript: How to Capture Highlighted Text

Subscribe to my newsletter and never miss my upcoming articles

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 quickly Tweeting, Editing, or sharing a link. The image below has an example of what I’m talking about.

2018-12-07-17_21_06-Everything-you-need-to-know-about-tree-data-structures.png

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 on how you could do this differently.

This could be used as a neat feature to add more UX options to your site. Allowing people to quickly share links on the web is essential for getting our content around.

No Comments Yet