Clear Text Selection with JavaScript

JavascriptJquery

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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();
    }
}

Solution 3 - Javascript

State of De-selection Affairs 2014

I did some research of my own. Here's the function I wrote and am using these days:

(function deselect(){
  var selection = ('getSelection' in window)
    ? window.getSelection()
    : ('selection' in document)
      ? document.selection
      : null;
  if ('removeAllRanges' in selection) selection.removeAllRanges();
  else if ('empty' in selection) selection.empty();
})();

Basically, getSelection().removeAllRanges() is currently supported by all modern browsers (including IE9+). This is clearly the correct method moving forward.

Compatibility issues accounted for:

  • Old versions of Chrome and Safari used getSelection().empty()
  • IE8 and below used document.selection.empty()

Update

It's probably a good idea to wrap up this selection functionality for re-use.

function ScSelection(){
  var sel=this;
  var selection = sel.selection = 
    'getSelection' in window
      ? window.getSelection()
      : 'selection' in document
        ? document.selection
        : null;
  sel.deselect = function(){
    if ('removeAllRanges' in selection) selection.removeAllRanges();
    else if ('empty' in selection) selection.empty();
    return sel; // chainable :)
  };
  sel.getParentElement = function(){
    if ('anchorNode' in selection) return selection.anchorNode.parentElement;
    else return selection.createRange().parentElement();
  };
}

// use it
var sel = new ScSelection;
var $parentSection = $(sel.getParentElement()).closest('section');
sel.deselect();

I've made this a community wiki so that you people can add functionality to this, or update things as the standards evolve.

Solution 4 - Javascript

2021 answer

  • removeAllRanges() is supported by most browsers, except Safari on macOS or iOS.

  • empty() is an alias for removeAllRanges() and supported by all browsers, including very old ones, with the exception of IE. This alias is defined in the specification, so should be safe to rely on.

Conclusion

Just use getSelection().empty(). There is no need for helper functions, nested ternary ifs, constructors, and whatnot Ninja banzai from the other answers. Perhaps needed ten years ago, but not any more.

If you really need IE support you can test for document.selection:

(window.getSelection ? window.getSelection() : document.selection).empty()

(not tested on IE)

Solution 5 - Javascript

Here's the accepted answer, but in two lines of code:

var selection = window.getSelection ? window.getSelection() : document.selection ? document.selection : null;
if(!!selection) selection.empty ? selection.empty() : selection.removeAllRanges();

The only check I don't do is for the existence of removeAllRanges - but AFAIK there is no browser that has either window.getSelection or document.selection but doesn't have either a .empty or .removeAllRanges for that property.

Solution 6 - Javascript

add this to your script to prevent right clicking and text selecting.

Exceptions can be added to var 'om'.

var d=document,om=['input','textarea','select'];;
function ie(){if(d.all){(mg);return false;}}function mz(e){if(d.layers||(d.getElementById&&!d.all)){if(e.which==2||e.which==3){(mg);return false;}}}if(d.layers){d.captureEvents(Event.mousedown);d.onmousedown=mz;}else{d.onmouseup=mz;d.oncontextmenu=ie;}d.oncontextmenu=new Function('return false');om=om.join('|');function ds(e){if(om.indexOf(e.target.tagName.toLowerCase())==-1);return false;}function rn(){return true;}if(typeof d.onselectstart!='undefined')d.onselectstart=new Function('return false');else{d.onmousedown=ds;d.onmouseup=rn;}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionman1View Question on Stackoverflow
Solution 1 - JavascriptGert GrenanderView Answer on Stackoverflow
Solution 2 - JavascriptTim DownView Answer on Stackoverflow
Solution 3 - JavascriptChaseMoskalView Answer on Stackoverflow
Solution 4 - JavascriptMartin TournoijView Answer on Stackoverflow
Solution 5 - JavascriptGrinnView Answer on Stackoverflow
Solution 6 - Javascriptuser2180104View Answer on Stackoverflow