javascriptselection

Is there a function to deselect all text using JavaScript?


Is there a function in javascript to just deselect all selected text? I figure it's got to be a simple global function like document.body.deselectAll(); or something.


Solution

  • Try this:

    function clearSelection()
    {
     if (window.getSelection) {window.getSelection().removeAllRanges();}
     else if (document.selection) {document.selection.empty();}
    }
    

    This will clear a selection in regular HTML content in any major browser. It won't clear a selection in a text input or <textarea> in Firefox.