Prevent text selection after double click

Prevent text selection after double click

I’m handling the dblclick event on a span in my web app. A side-effect is that the double click selects text on the page. How can I prevent this selection from happening?


Solution 1:

function clearSelection() {
    if(document.selection && document.selection.empty) {
    } else if(window.getSelection) {
        var sel = window.getSelection();

You can also apply these styles to the span for all non-IE browsers and IE10:

span.no_selection {
    -webkit-user-select: none; /* webkit (safari, chrome) browsers */
    -moz-user-select: none; /* mozilla browsers */
    -khtml-user-select: none; /* webkit (konqueror) browsers */
    -ms-user-select: none; /* IE10+ */

Solution 2:

In plain javascript:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

Or with jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });

Solution 3:

To prevent text selection ONLY after a double click:

You could use MouseEvent#detail property.
For mousedown or mouseup events, it is 1 plus the current click count.

document.addEventListener('mousedown', function (event) {
  if (event.detail > 1) {
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
}, false);


Related:  Are clearTimeout and clearInterval the same?

Solution 4:

FWIW, I set user-select: none to the parent element of those child elements that I don’t want somehow selected when double clicking anywhere on the parent element. And it works! Cool thing is contenteditable="true", text selection and etc. still works on the child elements!

So like:

<div style="user-select: none">

Solution 5:

A simple Javascript function that makes the content inside a page-element unselectable:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; }; = "none"; = "none";
    elem.unselectable = "on";

Solution 6:

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well