Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable text selection in textarea

I need to find a way to prevent users from selecting text in a textarea. The goal is to create a custom keyboard that is used to enter text in the textarea. I want users to be able to click on the textarea to set the caret position (which is already working right now). However, I don't want the users to be able to select certain parts of the inserted text, or there should at least be no visual indication of this. I have already tried a few things, such as the following CSS, but without success.

textarea {
    -moz-user-select: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    user-select: none;
}

The solution can be in CSS and/or JavaScript, and it only has to work in Google Chrome.


Disabling the textarea will not work for me. As I mentioned, I want users to be able to place the caret at certain positions by clicking on the location. If I would disable the textarea, this functionality would be lost.

like image 498
Bram W. Avatar asked Oct 02 '13 13:10

Bram W.


1 Answers

A combination of the "readonly" property and "user-select" property works.

The 2nd rule disables the highlighted border on select, which is a kind of visual selection.

The "unselectable" property seems to be Opera/IE specific.

the styles:

.noselect {
   cursor: default;
   -webkit-user-select: none;
   -webkit-touch-callout: none;
   -khtml-user-select: none;
   -moz-user-select: none;
   -ms-user-select: none;
   -o-user-select: none;
}

.noselect:focus {
   outline: none;
}

the markup:

<textarea class="noselect" readonly="readonly" unselectable="on"></textarea>

read-only might be more suitable than disabled (one can still toggle with JS, upon click event).

like image 108
Martin Zeitler Avatar answered Sep 18 '22 19:09

Martin Zeitler