how to use variables when setting CSS properties in Jquery?


Tags: jquery,css,jquery-mobile

Problem :

I'm trying to get the following to work:

var $marPad = $('#wrapper').attr('id') == "overthrow" ? 
      ["margin-top", "margin-bottom"] : ["padding-top", "padding-bottom"];

$("#toBeSet").css({ 
    $marPad[0] : "100px", 
    $marPad[1] : "100px"
    })  

This way I was hoping to get by with only a single css setter. However Firebug always tells me I cannot make a CSS selector like so $marPad[0]. It always returns missing : after property id.

Can someone tell me what I'm doing wrong and if it's possible at all to also use variables instead of fixed CSS selectors?

Thanks for help!



Solution :

You need to first create the object, then add properties to it.

var obj = {}; 

obj[$marPad[0]] = '100px';
obj[$marPad[1]] = '100px';

$("#toBeSet").css(obj);

Perhaps better would be to make it part of the conditional statement in the first place...

var $marPad = $('#wrapper').attr('id') == "overthrow" ? 
      {marginTop:'100px', marginBottom: '100px'} : {paddingTop:'100px', paddingBottom:'100px'};

$("#toBeSet").css($marPad);

    CSS Howto..

    How to create custom CSS “on the fly” based on account settings in a Django site?

    How to rearrange these elements with CSS?

    How to give style (image) for browse button in CSS?

    How to dynamically generate CSS3 keyframe steps using SASS?

    How do I add line-height to a