You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.
If you're targeting decent browsers only, then just make use of CSS3:
.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<label class="unselectable">Unselectable label</label>
If you'd like to cover older browsers as well, then consider this JavaScript fallback:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734</title>
<script>
window.onload = function() {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
disableSelection(labels[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function() { return false; };
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function() { return false; };
}
}
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
If you're already using jQuery, then here's another example which adds a new function disableSelection()
to jQuery so that you can use it anywhere in your jQuery code:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2310734 with jQuery</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.fn.extend({
disableSelection: function() {
this.each(function() {
if (typeof this.onselectstart != 'undefined') {
this.onselectstart = function() { return false; };
} else if (typeof this.style.MozUserSelect != 'undefined') {
this.style.MozUserSelect = 'none';
} else {
this.onmousedown = function() { return false; };
}
});
}
});
$(document).ready(function() {
$('label').disableSelection();
});
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
MozUserSelect
only. New browsers will use no prefix. Look at the list of all possible javascript prefixes: ['Moz', 'Webkit', 'ms', 'O', 'Khtml', ''] /*with empty string for no prefix*/. You should correctly deal with camelCase. And it's a serious bug that you are overwritingonselectstart
andonmousedown
event handlers with your function, so previously attached handlers do not work any more. I can Update your code if you like – Balsa