jquery

Setting jQuery .css() within "for .. in" loop


This works OK:

$(container_elm).css({
  'border-width':'1px'
})

Now I am trying to pass CSS propertyName : value as a parameter to a function:

function my_func(css_arr) {
  if (css_arr!==null && css_arr!=='') {
    for(var x in css_arr) {
      if(css_arr.hasOwnProperty(x)) {
        y=css_arr[x];
        x_new='"'+x+'"';
        y_new='"'+y+'"';

        $(container_elm).css({
            //'border-width':'1px' // this works
            //x:y // this does NOT work
            //x_new:y_new // this does NOT work
        });
        //console.log(x_new, y_new); //returns "border-width" "1px"
        //console.log(x, y); //returns border-width 1px
      }
    }
  }
}

//usage
my_func({'border-width':'1px'});

How can I pass CSS object "propertyName : value", and make .css() receive it and work?

Edit

Demo - http://jsfiddle.net/BRwzF/5/


Solution

  • I totally agree with what @Somkittens suggested. Just want to brief you about why x_new:y_new did not work for you.

    In .css() jquery function, a key/property does not get parsed or treated as a variable, so putting $('dom').css('width': '100px') or $('dom').css(width: '100px') does not make any difference. We wrap properties in quotes in case it has hyphens in it. i.e. border-radius, -webkit-border-radius etc.

    But still if you want to go with your solution, in that case you have tweak your code a bit which does the same thing as @SomeKittens's

     y=css_arr[x];
     x_new=x;
     y_new=y;
     var foobar = {};
         foobar[x_new] = y_new;
     $(container_elm).css(foobar);
    

    Demo: http://jsfiddle.net/4tBVH/