Yamiteru Iori
Yamiteru Iori

Reputation: 121

disable text selection on double click

I have script that toggles menu from the side:

<script>
    // Closes the sidebar menu
    $("#menu-close").click(function (e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });
    // Opens the sidebar menu
    $("#menu-toggle").click(function (e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });
</script>

and I use this in every section tag:

ondblclick = $("#menu-close").click()

but the problem is that when I double click somewhere it also selects text. The question is: How can I disable this double click selection on the whole page? It'd be cool if I could implement it into my actual script.

UPDATE: now I have

document.getElementById("el").ondbclick = function(ev) {
    ev.preventDefault()
    alert()
    return false}

$("#menu-close").click(function (e) {
    e.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
});
// Opens the sidebar menu
$("#menu-toggle").click(function (e) {
    e.preventDefault();
    $("#sidebar-wrapper").toggleClass("active");
});

and id="el" on elements I don't want to be selected.. but it still doesnt work

Upvotes: 12

Views: 17765

Answers (3)

Abishek H
Abishek H

Reputation: 209

(element).querySelector('mousedown', (e) => {
    e.preventDefault()
})

In Plain JavaScript...

Upvotes: 4

CoderPi
CoderPi

Reputation: 13211

Use these CSS-Rules on the Element:

#menu-close {
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Do this on every Element that should not be selected. Or just on body { for everything.


You could also remove the double-click selection after it happened, if you don't want to disable selection everywhere:

document.getElementById("el").ondbclick = function(ev) {
  ev.preventDefault()
  alert()
  return false
}
<div id="el"> asd</div>

Upvotes: 31

Hemal
Hemal

Reputation: 3760

You can apply class like this

.unselectable {
   -moz-user-select: none;
   -khtml-user-select: none;
   -webkit-user-select: none;
   -ms-user-select: none;
   user-select: none;
}

Upvotes: -2

Related Questions