sebalinwy
sebalinwy

Reputation: 15

JS: css property and value in one variable

var trns1 = '"transition": "all 1s"';

Why doesn't that work?

$('#box').css({"transform": "translate(xy)", trns1 });

Shouldn't that be exactly the same like:

$('#box').css({"transform": "translate(xy)", "transition": "all 1s" });

Upvotes: 0

Views: 36

Answers (1)

Djave
Djave

Reputation: 9329

Nope. Your JavaScript object isn't correct – you can't add a string in and expect it to work as a key value pair.

This will work:

var trns1 = { "transition": "all 1s"};
$('#box').css(trns1);

If you needed to add more options, you could do so easily:

var trns1 = { "transition": "all 1s"};
trans1.color = 'red';
trans1.height = '20px';
$('#box').css(trns1);

At the end of this trans1 would be

{
    'color' : 'red',
    'height' : '20px',
    'transition': 'all 1s'
}

Edit

Based on your comment you can easily chain events in jQuery.

var trns1 = {"transition": "all 0.3s ease"};
var trns2 = {"transform": "translateY(4vw)"};

And then use them like this:

$('#box').css(trns1).css(trns2);

Upvotes: 2

Related Questions