Saturday, July 23, 2011

How to prevent text selection

There are few ways

1. Apply 'preventDefault' for events 'onselectstart' and 'onmousedown'

var element = document.getElementById('content');
element.onselectstart = function () { return false; }
element.onmousedown = function () { return false; }

2. Add attribute 'unselectable'

$(document.body).attr('unselectable', 'on')

3. Add style 'user-select: none'

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

4. Use disabled textarea
<textarea disabled="disabled" style="border:none;color:#000;background:#fff; font-family:Arial;">
    how to prevent text selection?
textarea>

source (ru): javascript tips #2 

No comments :