Is there a function to deselect all text using JavaScript?

JavascriptSelection

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

For Internet Explorer, you can use the http://msdn.microsoft.com/en-us/library/ms536359(v=vs.85).aspx">empty method of the document.selection object:

> document.selection.empty();

For a cross-browser solution, see this answer:

https://stackoverflow.com/questions/6186844/clear-a-selection-in-firefox/6187098#6187098

Solution 4 - Javascript

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

Solution 5 - Javascript

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

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
QuestionNoodleOfDeathView Question on Stackoverflow
Solution 1 - JavascriptAnkurView Answer on Stackoverflow
Solution 2 - JavascriptTim DownView Answer on Stackoverflow
Solution 3 - JavascriptLuke GirvinView Answer on Stackoverflow
Solution 4 - JavascriptDan OrtegaView Answer on Stackoverflow
Solution 5 - JavascriptJohnView Answer on Stackoverflow