Mohan Selvaraj
Mohan Selvaraj

Reputation: 276

How to Disable Text selection on firefox in javascript

I'm using this CSS to disable text selection. It works in Chrome and Safari, but not in Firefox

*.e-pdfviewer-pageCanvas {
    -moz-user-select: -moz-none !important;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

*.e-pdfviewer-pageCanvas * {
    -moz-user-select: text;
    -khtml-user-select: text;
    -webkit-user-select: text;
    -o-user-select: text;
    user-select: text;
}

Upvotes: 1

Views: 1144

Answers (2)

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7787

Try this simple jQuery plugin:

jQuery.fn.extend({
    disableSelection : function() {
        this.each(function() {
            this.onselectstart = function() { return false; };
            this.unselectable = "on";
            jQuery(this).css({
                 '-moz-user-select': 'none'
                ,'-o-user-select': 'none'
                ,'-khtml-user-select': 'none'
                ,'-webkit-user-select': 'none'
                ,'-ms-user-select': 'none'
                ,'user-select': 'none'
            });
        });
    }
});

$('.e-pdfviewer-pageCanvas').disableSelection();

Upvotes: 1

Angel Politis
Angel Politis

Reputation: 11313

With the following code you can disable text selection in the entire webpage, except inputs and textareas:

document.getElementsByTagName("BODY")[0].onselectstart = function(e) {
    if (e.target.nodeName != "INPUT" && e.target.nodeName != "TEXTAREA") {
        e.preventDefault();
        return false;
    }
    return true;
};

Alternatively, if you want to disable text selection completely you can use this code:

document.getElementsByTagName("BODY")[0].onselectstart = function(e) {
    e.preventDefault();
    return false;
};

If you want to disable text selection only for the elements having the class .e-pdfviewer-pageCanvas you can use:

var pdfviewer = document.getElementsByClassName("e-pdfviewer-pageCanvas");

for (var i = 0; i < pdfviewer.length; i++) {
    pdfviewer[i].onselectstart = function(e) {
        e.preventDefault();
        return false;
    };
};

[EDIT]:

If none of the aforementioned solved your issue, use the following code in your HTML <body> or the element you want to disable text selection for specifically:

<body onselectstart = "return false;" style = "-moz-user-select: none;">...</body>

Or in JavaScript:

document.getElementsByTagName("BODY")[0].onselectstart = function(e) {return false};

document.getElementsByTagName("BODY")[0].style.mozUserSelect = "none";

Upvotes: 3

Related Questions