0

I mean - can this:

var prefix = 'webkit';
element.style['marginTop'] = '20px';
element.style[prefix + 'Transform'] = 'translate(100%, 0, 0)';

be rewritten into a single statement?

In jQuery there's css() which accepts an object with properties, but it doesn't work when properties are made out of variables

$(element).css({
  marginTop: '20px',
  prefix + 'Transform': 'translate(100%, 0, 0)'  // doesn't work
});
thelolcat
  • 10,995
  • 21
  • 60
  • 102
  • possible duplicate of [How to set multiple css style properties in Javascript](http://stackoverflow.com/questions/3968593/how-to-set-multiple-css-style-properties-in-javascript) – dsgriffin Mar 11 '14 at 23:24
  • ok but there's no good answer there... – thelolcat Mar 11 '14 at 23:25
  • Try `$(element).css({ marginTop: '20px' }).css(prefix + 'Transform', 'translate(100%, 0, 0)');` I think that is the best that can be done other than creating a dynamic object – Arun P Johny Mar 11 '14 at 23:26
  • possible duplicate of [Setting multiple attributes for an element at once with JavaScript](http://stackoverflow.com/questions/12274748/setting-multiple-attributes-for-an-element-at-once-with-javascript) – dsgriffin Mar 11 '14 at 23:26
  • 1
    The first part of the *object literal* you are passing in can't be a variable. That's correct. Why would you want to do that, anyway? When using jQuery, you don't have to worry about vendor prefixes... – random_user_name Mar 11 '14 at 23:26
  • What do you mean I don't have to worry about prefixes? Does jQuery add them? – thelolcat Mar 11 '14 at 23:28
  • depends on the version of jQuery you are using? 1.8+ does it – Arun P Johny Mar 11 '14 at 23:36
  • it doesn't. I just tried it – thelolcat Mar 11 '14 at 23:41
  • ok it does but some properties don't appear :/ – thelolcat Mar 11 '14 at 23:47

2 Answers2

0

One way to do this kind of thing is using CSS hooks. You define the hook and then set the individual properties you need, and the hook takes care of extra processing like adding prefixes. http://api.jquery.com/jQuery.cssHooks/

It might be overkill if your site is very simple, but if you're making any kind of substantially interactive site that needs to be perfect in all browsers, hooks can make applying CSS a lot simpler.

The other way is to add your CSS styles that you manually apply as classes, and add/remove those classes when necessary.

Derek
  • 4,575
  • 3
  • 22
  • 36
0

This should work

element.style.cssText = "marginTop: 20px; " + prefix + "Transform: translate(100%, 0, 0);";

But you are looking for a way with jQuery, right?

In that case you can do

var styles = {};

styles['marginTop'] = '20px';
styles[prefix + 'Transform'] = 'translate(100%, 0, 0)';

$(element).css(styles);

If you can it is better to use classes for your styles so you can separate the logic from the output which is definitely best practice.

nils
  • 1,668
  • 14
  • 15