2

I have seen plenty of threads asking how to use a variable for jquery's css method like

var black='#000000';
$(this).css({'color':black});

but none of how to use variables the other way round like

var bg='background-color';
$(this).css({bg:'#000000'});

For me it doesn't work like that, so I am asking, is there a way to make something like that work, to save some space when using 'background-color' a bunch of times in a script?

Thanks!

1
  • 2
    How about var obj={}; obj[bg]=black; $(this).css(obj) ? Commented Mar 3, 2016 at 10:29

3 Answers 3

5

if it's a single property you could write in this way

var bg = 'background-color';
$(this).css(bg, '#000000');

if you need to pass an object you could define the background-color key as a variable inside squared brackets

var bg = 'background-color';

var obj = {};
obj[bg] = '#000000';
$(this).css(obj);
Sign up to request clarification or add additional context in comments.

3 Comments

OP wants to pass object as argument...You can not set many styles using syntax provided by you..
@RayonDabre I don't see this as a strict requirement for the OP: “is there a way to make something like that“ - anyway I've edited and show both the ways
This obj method just saved my bacon, it's a really nice method.
2

Use bracket notation to use variable as key of the object

var obj = {};
var bg = 'background-color';
var black = '#000000';
obj[bg] = black;
$('div').css(obj)
div {
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>Hello</div>

Comments

1

Just use the version of .css(propertyName, value) that takes the style name and parameter

$('div').each(function() {
  var bg = 'background-color';
  $(this).css(bg, '#000000');
})
div {
  margin-bottom: 5px;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>some</div>
<div>test</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.