140

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.

6 Answers 6

239

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I can confirm that window.getSelection().removeAllRanges(); works in all current browsers. Live demo: jsfiddle.net/hWMJT/1
you have to click a button like <input id='but' type='button' value='click'/ onclick='clearSelection()'>
@Šime - not really. It's "working" because the selection is lost when the button get focus. Proof - code is commented, selection is still cleared.
@Shadow Here is the proper demo: 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.
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!
|
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;
            }
        }
    }
}

3 Comments

doesn't work if your selection starts somewhere from the first line and includes the larger text field
@VyachaslavGerchicov: That's probably because it's a quickly-made simple example and if you end the selection outside the main <div> then the mouseup event doesn't fire. Put the mouseup handler on the document instead and it would be fine: jsfiddle.net/SLQpM/23
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.
10

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

1 Comment

When using collapseToEnd (), an error appears in the console - Uncaught DOMException: Failed to execute 'collapseToEnd' on 'Selection': there is no selection.
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

6 Comments

If your website is public (not intranet where you control the browsers) it's not good idea, it's not cross browser.
@Shadow Wizard - true, this question may be relevant for a cross-browser solution: stackoverflow.com/questions/6186844/…
@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.
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.
@Luke document.selection.clear() works only in IE. See here: 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.
|
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);

Comments

0

This is a super old thread, but I came up with a "dumb" solution (which probably doesn't work for all use cases).

// Select any input, focus on it, then blur (if needed).
document.getElementsByTagName("input")[0].focus()
document.getElementsByTagName("input")[0].blur()

Alternatively, re-focus on the last element your mouse cursor was hovering over.

// Get all current notes with ":hover" pseudo element.
const hoverNodes = document.querySelectorAll(":hover")
// Get the last Node in the list (zero-indexed).
const lastNode = hoverNodes.item(hoverNodes.length-1)
// Set focus on a random input
// Note: this could be made more flexible with a check or two for an element's existence.
//  Maybe just focusing on a random "div" would be better?
document.getElementsByTagName("input")[0].focus()
// Set focus to that hover node.
lastNode.focus()

I shamelessly copied a JSFiddle from another solution and updated with this solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.