Javascript – Highlighting Selected Text

I am sure we all have been at a point when we need to highlight something, and most note taking or sharing software allows you to pick and color and go selection crazy. Luckily, however, it is actually surprisingly easy to get a selection and highlight it with Javascript.

To start, why not take a second and just selected some text this tutorial. You should have just highlighted some text green, as I have included the necessarily Javascript to allow highlighting in any paragraph in the content section of the tutorial. That’s right, you can highlight any text you want in the confines of the tutorial.

It all is thanks to a simple span, which has a css class that changes the color of the text inside it. The only trick is to retrieve and surround the text that was selected by the user with this span. Thankfully, there is some simple code, that is cross-browser compatible, that will allow us to do this really easily. Let’s start with getting the selected text;

function highlightSelection()  {
  var selection;

  //Get the selected stuff
  if(window.getSelection)
    selection = window.getSelection();
  else if(typeof document.selection!="undefined")
    selection = document.selection;
}

The lines above get the selected text, with the only difference in the if statement being how you retrieve it in different browsers. Between these two methods, you can get text selections in any modern browser.

Next we have to get the selection “range” which represents a single block of selected text. In the case of just one selection, there will always be one range. However, it is possible to select more than one block of text, either by holding down the control button or using some other means. The point is that you have to retrieve a range object. In our case, we are keeping it simple and just retrieving the first range:

function highlightSelection()  {
  var selection;

  //Get the selected stuff
  if(window.getSelection)
    selection = window.getSelection();
  else if(typeof document.selection!="undefined")
    selection = document.selection;

  //Get a the selected content, in a range object
  var range = selection.getRangeAt(0);
}

That’s it. You just have to call a simple function and tell it what range you want. As noted above, we just want the first range, i.e. the range at index zero.

Now for the fun part. Next we have to take the range and wrap it in a span tag. Before we do this, we have to make a few checks. First we have to make sure the range is defined and that the selection is not “collapsed”, i.e. the start and end points of the selection are the same. This prevents us from trying to wrap an empty selection.

Second we are going to add a simple check that prevents wrapping tags inside our span, which could break our entire html document. This is a simple method that will save our poor HTML document from getting ripped apart. While it is possible to wrap text across multiple tags, for now we are playing it on the safe side and keeping things as simple as possible.

Our final function will look like so:

function highlightSelection()  {
  var selection;

  //Get the selected stuff
  if(window.getSelection)
    selection = window.getSelection();
  else if(typeof document.selection!="undefined")
    selection = document.selection;

  //Get a the selected content, in a range object
  var range = selection.getRangeAt(0);

  //If the range spans some text, and inside a tag, set its css class.
  if(range && !selection.isCollapsed)
  {
    if(selection.anchorNode.parentNode == selection.focusNode.parentNode)
    {
      var span = document.createElement(‘span’);
      span.className = ‘highlight-green’;
      range.surroundContents(span);
    }
  }
}

The first check we make is fairly straightforward, but the tricky part comes in the second check. Here we are checking the parent of the anchor node, which is where the selection started. Then we make sure the focus node’s parent is the same, which is where the selection has ended. Basically we make sure the range starts and ends in the same tag, thus preventing us from trying to wrap selections that span multiple tags.

Since we also use a css class, the style possibilities are endless. You can even have buttons that change the highlighter style. All you have to do is change the class of the span that is used to wrap the text. For example, the CSS I used in this demo looks like so:

.highlight-green {
  color: #00FF00;
}

So this wraps it up for this tutorial. Just remember when you need coding help, all you have to do is Switch On The Code.

Leave a Reply

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