Javascript Code of the Day: get highlighted text

Discovered the code below while browsing online. Inspired from codetoad.com.

1
2
3
4
5
6
function getHighlightedText(){
     return ((window.getSelection) ? window.getSelection() 
          : (document.getSelection) ? document.getSelection()
          : (document.selection) ? document.selection.createRange().text 
          : null);
}

Usage

1
getHighlightedText();   // returns highlighted material as a string.
(Page view Count: 423)