131

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.

rolling_codes
  • 15,174
  • 22
  • 76
  • 112

5 Answers5

227

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.

John
  • 1
  • 13
  • 98
  • 177
Ankur
  • 3,584
  • 1
  • 24
  • 32
  • 34
    I can confirm that `window.getSelection().removeAllRanges();` works in all current browsers. **Live demo:** http://jsfiddle.net/hWMJT/1/ – Šime Vidas Jul 03 '11 at 12:18
  • you have to click a button like – Ankur Jul 03 '11 at 12:23
  • 1
    @Šime - not really. It's "working" because the selection is lost when the button get focus. [Proof](http://jsfiddle.net/hWMJT/2/) - code is commented, selection is still cleared. – Shadow The GPT Wizard Jul 03 '11 at 12:39
  • @Shadow Here is the proper demo: http://jsfiddle.net/9spL8/3/ The `removeAllRanges()` method works in all current browsers for text inside paragraphs or similar non-form-field elements. For form-fields (like textarea), this method doesn't work in IE9 and FF5. – Šime Vidas Jul 03 '11 at 13:37
  • @Shadow The second method - `document.selection.empty()` - works in IE9 for all types of selections (even form-fields). Therefore, the above code works in all current browsers except for the Firefox/form-field combination (for which there should exist a hack). – Šime Vidas Jul 03 '11 at 13:42
  • 1
    Edited, use `window.getSelection().removeAllRanges();` *first* because it's standards-compliant, proprietary code should always be executed *last*. Be it the year 2004 or 4004 standards compliant code will always ultimately be what we use so detect it first without exception! – John Feb 23 '18 at 00:26
  • This causes the caret in a contenteditable div to disappear. – Johann Aug 20 '18 at 13:54
29

Here's a version that will clear any selection, including within text inputs and textareas:

Demo: http://jsfiddle.net/SLQpM/23/

function clearSelection() {
    var sel;
    if ( (sel = document.selection) && sel.empty ) {
        sel.empty();
    } else {
        if (window.getSelection) {
            window.getSelection().removeAllRanges();
        }
        var activeEl = document.activeElement;
        if (activeEl) {
            var tagName = activeEl.nodeName.toLowerCase();
            if ( tagName == "textarea" ||
                    (tagName == "input" && activeEl.type == "text") ) {
                // Collapse the selection to the end
                activeEl.selectionStart = activeEl.selectionEnd;
            }
        }
    }
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • doesn't work if your selection starts somewhere from the first line and includes the larger text field – Vyachaslav Gerchicov Apr 26 '16 at 08:21
  • 1
    @VyachaslavGerchicov: That's probably because it's a quickly-made simple example and if you end the selection outside the main `
    ` then the `mouseup` event doesn't fire. Put the mouseup handler on the document instead and it would be fine: http://jsfiddle.net/SLQpM/23/
    – Tim Down Apr 26 '16 at 13:29
  • This is a great work-around in older browsers that don't support user-select CSS when dragging elements around. Call clearSelection() in the mouse move callback. – Geordie Mar 10 '17 at 00:32
7

This worked incredibly easier for me ...

document.getSelection().collapseToEnd()

or

document.getSelection().removeAllRanges()

Credits: https://riptutorial.com/javascript/example/9410/deselect-everything-that-is-selected

Dan Ortega
  • 1,679
  • 17
  • 13
  • When using collapseToEnd (), an error appears in the console - Uncaught DOMException: Failed to execute 'collapseToEnd' on 'Selection': there is no selection. – Alexander V. Ulyanov May 05 '21 at 14:58
7

For Internet Explorer, you can use the empty method of the document.selection object:

document.selection.empty();

For a cross-browser solution, see this answer:

Clear a selection in Firefox

Community
  • 1
  • 1
Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
  • 1
    If your website is public (not intranet where you control the browsers) it's not good idea, it's not cross browser. – Shadow The GPT Wizard Jul 03 '11 at 12:17
  • 2
    @Shadow Wizard - true, this question may be relevant for a cross-browser solution: http://stackoverflow.com/questions/6186844/clear-a-selection-in-firefox – Luke Girvin Jul 03 '11 at 12:17
  • 1
    @Luke nice, too bad that another website is going to be (probably) not consistent among different browsers as the OP took what you gave as-is. – Shadow The GPT Wizard Jul 03 '11 at 12:42
  • 1
    In my opinion browser compatibility is something obvious that should be offered by us - many developers aren't even aware such differences exist, so those who know should tell them. This aside, I never said your question is *wrong*, just *missing*. – Shadow The GPT Wizard Jul 03 '11 at 12:56
  • 1
    @Luke `document.selection.clear()` works **only** in IE. See here: http://jsfiddle.net/9spL8/4/ Also, this method will *remove* the selected text, not just deselect it. To just deselect the text, use `document.selection.empty()` instead. – Šime Vidas Jul 03 '11 at 13:47
  • My mistake, it is Internet Explorer only, and the method should be empty not clear - I've edited my answer to reflect this. – Luke Girvin Jul 03 '11 at 14:03
0

For a textarea element with at least 10 characters the following will make a small selection and then after a second and a half deselect it:

var t = document.getElementById('textarea_element');
t.focus();
t.selectionStart = 4;
t.selectionEnd = 8;

setTimeout(function()
{
 t.selectionStart = 4;
 t.selectionEnd = 4;
},1500);
John
  • 1
  • 13
  • 98
  • 177