views:

68

answers:

1

I'd like to set vendor styles with Javascript, something like this:

elem.style.mozBorderRadius = '5px';

Is this possible? If so, how?

+1  A: 

You can check for and set it like this:

if (elem.style.MozBorderRadius !== undefined)
  elem.style.MozBorderRadius = "5px";

You can do this for webkit as well while you're at it as well using webkitBorderRadius, like this:

if (elem.style.MozBorderRadius !== undefined)
   elem.style.MozBorderRadius = "5px";
else if (elem.style.webkitBorderRadius !== undefined)
   elem.style.webkitBorderRadius = "5px";

Make sure to wrap it in an if() like I have above, so it doesn't error in browsers that don't support it.

Nick Craver
Just figured this out a second before you posted by performing a for ( prop in elem.style ) loop and tracing out the results. Thanks!
bobthabuilda
Don’t you mean `if (typeof elemen.style.MozBorderRadius !== undefined`)?
Mathias Bynens
Also, in which browser(s) does setting `elem.style.MozBorderRadius` throw a warning or an error? I couldn’t find any. Same goes for `webkitBorderRadius`.
Mathias Bynens
@Mathias - Nope, not in this case...you can see this working here (tested in IE, Chrome, Firefox): http://jsfiddle.net/X8839/
Nick Craver
@Mathias - The call itself probably won't error itself since `elem.style` is there and you're just extending it in that case, but any code that may be looking for elements with the property set, etc. may have very unpredictable results, best to not set it and cause any errors down the line.
Nick Craver
@Nick: I know it ‘works’, but you still need to use `typeof` to check for `undefined`ness in a foolproof/bulletproof way. See http://jsfiddle.net/mathias/2Bvrh/ (without `typeof`) vs. http://jsfiddle.net/mathias/rbT33/ (with `typeof`).
Mathias Bynens
@Mathias - I absolutely agree in 90%+ of cases...this just isn't one of them because of this being only the past property on the chain that may be `undefined`, so the functionality and error handling *for the example* is equivalent.
Nick Craver