views:

94

answers:

3

Simple question which I can't find the answer to: how can I use JavaScript (or jQuery) to deselect any text which may be selected on a webpage? E.G. user clicks and drags to highlight a bit of text -- I want to have a function deselectAll() which clears this selection. How should I go about writing it?

Thanks for the help.

A: 

window.getSelection() lets you access the selected text, from there, there's a few things you can do to manipulate it..

Read More: Developer Mozilla DOM Selection

Zuul
+5  A: 
if (window.getSelection) {
  if (window.getSelection().empty) {  // Chrome
    window.getSelection().empty();
  } else if (window.getSelection().removeAllRanges) {  // Firefox
    window.getSelection().removeAllRanges();
  }
} else if (document.selection) {  // IE?
  document.selection.empty();
}

Credit to Mr. Y.

Gert G
This works beautifully. Cheers!
Matt Nichols
Thanks. I'm glad it solved your issue. :)
Gert G
This assumes that the existence of `document.selection` implies the existence of an `empty()` method of it. You've tested for the method in every other case, so you might as well test for `empty` in the final case too.
Tim Down
+1  A: 

Best to test the features you want directly:

var sel = window.getSelection ? window.getSelection() : document.selection;
if (sel) {
    if (sel.removeAllRanges) {
        sel.removeAllRanges();
    } else if (sel.empty) {
        sel.empty();
    }
}
Tim Down