Chaitanya Chauhan
Chaitanya Chauhan

Reputation: 785

Passing dynamic property in css method

When i was doing like below, it was not working!! can you please help me why is it so?

var propertyName = 'left';
var propertyVal = $("body").width();

$('nav').css({ propertyName: propertyVal , 'position': 'absolute'});

Upvotes: 1

Views: 47

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Instead you can do this way:

$('nav').css(propertyName, propertyVal)
        .css('position', 'absolute');

Also you can use the array notation to add:

cssProperties[propertyName] = propertyVal

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you can't use a variable as the name of a property in an object using the syntax you have. Instead you need to use bracket notation to define that property and its value. Try this:

var cssSettings = { 'position': 'absolute' };
cssSettings[dynCssProperty] = widthMenu;
$('nav').css(cssSettings);

Alternatively, you can make two calls to the css() method, setting each attribute individually:

$('.nav').css('postion', 'absolute').css(dynCssProperty, widthMenu);

Upvotes: 2

Related Questions