Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function to deselect all text using JavaScript?

People also ask

How can you deselect the text?

In Windows, you can deselect the whole page selection (gained by pressing CTRL + A) by pressing CTRL + SHIFT + HOME. If you have a partial selection not starting from the beginning, the combo specified above will select the text from the beginning as far as the previously selected text.


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.


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

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


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