How to apply multiple styles using javascript variables?

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
});

Answers


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.


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.


Need Your Help

XAudio2, starting/stopping loops?

audio 3d loops xaudio2

How can I start/stop audio looping in IXAudio2SourceVoice?

Structure Map 2.6.1

c# generics structuremap

In my current project I'm currently trying to replace the Windsor IoC in favour of structure map (2.6.1). But having a bit of problem registering some generic types. How would I register IFilterCon...