Galaxy
Galaxy

Reputation: 3400

Using variables in .css() with Jquery

I'm running into a rather odd problem that I just can't seem to solve. I'm trying to use a variable in the .css() but it doesn't work. However if I type in 'background-color' directly within the .css() call it does. What gives?

var css = that.data('css');
var targets = that.data('targets');
var value = that.val();
console.log(css + ' ' + targets + ' ' + value);
console.log(css === 'background-color');
    // returns true

$(targets).css({
    css: value
});
// Doesn't work!

$(targets).css({
    'background-color': value
});
// Works ok!

Upvotes: 2

Views: 301

Answers (3)

user1832281
user1832281

Reputation: 154

This works too. Try removing the curly braces inside .css() and use a comma instead of colon.

   var css = 'background-color';
    var targets = '#hellowhat';
    var value = '#000';


 $(""+ targets +"").css(
        css, value);

Upvotes: 0

Guffa
Guffa

Reputation: 700152

You can't use a variable as an identifier in an object literal. Using { css: value } creates an object with a property named css, it's not using the variable css.

Create an object and set the property:

var o = {};
o[css] = value;
$(target).css(o);

Upvotes: 2

Musa
Musa

Reputation: 97672

You cannot use a variable as a key in an object literal, create the object first then use bracket notation to add the property

    var obj = {};
    obj[css] = value;
    $(targets).css(obj);

or simply

    $(targets).css(css, value);

Upvotes: 4

Related Questions