1

This is seemingly a duplicate, but read on for it is not quite so... I think... :) I have followed the answer here: How do I disable text selection with CSS or JavaScript? with a twist. I want to disable the selection programmatically for certain fields, and I do that in Chrome with:

node.style.webkitUserSelect="none";

Which works fine. However, I tried the following for Firefox:

node.style.mozUserSelect="none";

But this doesn't work. I haven't tried with any other browser. Is there a different way to do this? And is it a "documented standard" that all CSS rules like this:

.rule {
    some-css-selector: value;
}

is translatable to JavaScript like the following?

node.style.someCssSelector="value";

Or is it just luck that it happens to work in some cases?

Community
  • 1
  • 1
Mikael Lindqvist
  • 775
  • 5
  • 21
  • Try doing this on a few other browser specific css3 style attributes. I think user select is something that is implemented so differently between browsers. For instance, try this for border-radius and let us know what you find. Hopefully that will provide some insight to this issue. – andyzinsser Feb 20 '13 at 20:04

2 Answers2

4

With prefixed properties the prefix starts with a capital letter, so node.style.MozUserSelect="none";

Musa
  • 96,336
  • 17
  • 118
  • 137
  • Worked like a charm! Thanks! For the record, I also changed the crome specific code to node.style.WebkitUserSelect="none"; and it still works. So like you say, prefixed properties should start with a capital letter, it just seems like chrome was a bit more tolerant.. – Mikael Lindqvist Feb 20 '13 at 20:16
2

One option, is to create a CSS style and then programmatically add that class to the items you desire:

HTML

<div id="container">
  This is some text that should not be selectable!
</div>

CSS

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

JS

var container = document.getElementById("container");
container.className += " noselect";

jsfiddle

Ruben Infante
  • 3,125
  • 1
  • 17
  • 16
  • Ah, that is clever... However, in this particular case, for various reasons, which may or may not be well thought through, I would like to refrain from relying on classes in a CSS file. – Mikael Lindqvist Feb 20 '13 at 20:19