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"];

    $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';


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


    CSS Howto..

    how to add several td and tr in css

    jQuery - How to animate text simultaneously to color change transition

    CSS: How to make element appear from left of the screen?

    How to rotate + flip element with CSS

    how to set the absolute position div center align

    css breadcrumbs breaks into 2 lines, how to controll it in responsive?

    How to add fade in and fade out when changing between texts in javascript

    How do i make this form same on all browsers?

    How to vertical center ordered list-navigation

    How does css scale transform affect document flow?

    Google Share button not showing properly if originaly hidden

    How to Target Twitter Bootstrap <768px and 480px Breakpoints

    How to make a Floating Nav bar? [closed]

    How To Put Values Dynamically

    HTML/CSS: how to put text both right and left aligned in a paragraph

    How to make a div to represent a dotted line?

    Homepage build - How to use CSS more efficiency?

    Do East Asian (e.g. Chinese) characters have baselines? How do they align with English in CSS?

    How to change anchor color when you hover over a list

    How to prevent a span from breaking into the next line - responsive webdesign?

    How to calculate total size of all css,js and html pages separately uing shell script?

    How to add css box-shadow using .style javascript property

    How to automatically compile LESS into CSS on the server?

    How to improve the rendering of my HTML/CSS button?

    CSS - How to remove whitespace between anchored images

    How to adjust table or content in CSS when printing?

    How to add custom font for Avada WordPress Theme

    css “background-image” shows unwanted border, img “src” does not

    How to pop a dialog box /iframe/Lightbox like one below above the webpage content [closed]

    How to have multiple css print layouts on a single page application?