6

The following code to double an objects width and height works fine. I just can't understand why curly brackets are needed.

var target = $('#target');
target.css({
    width: target.width() * 2,
    height: target.height() * 2
});
Anders
  • 8,307
  • 9
  • 56
  • 88
Alvin
  • 81
  • 3
  • The curly braces are JS syntax for defining an object, which you are providing to the `css()` method. The object can be used to contain multiple properties which should be updated in a single call. – Rory McCrossan Dec 23 '15 at 13:26
  • 1
    Since javascript doesn't have direct syntax support for named parameters, it uses the idiom of passing an object literal to achieve the same thing. – Tim Seguine Dec 23 '15 at 13:39

3 Answers3

6

The curly brackets are needed because you are passing an object literal as a parameter to the jQuery .css function. According to the documentation you can use it like this:

.css( properties )
properties
Type: PlainObject
An object of property-value pairs to set.

So width and height are not two different parameters. They are two different properties of a single object, where the property name is the style to change and the property value the value to change it to.

Mozilla has the following to say about object literals:

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

If you for some reason want to avoid using object literals, you can do it like this:

target.css("width", target.width()*2);
target.css("height", target.height()*2);

Or this:

target.width(target.width()*2);
target.height(target.height()*2);
Anders
  • 8,307
  • 9
  • 56
  • 88
2

Curly braces {} are needed to set multiple CSS properties. Here you are trying to set width and height.

Just check here for more info on this and here is an official jquery api reference.

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
-2

I think you have to use this

var target=$('#target');
target.css("width",target.width()*2);
target.css("height",target.height()*2);