Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are curly brackets needed when using jQuery to adjust width and height?

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
});
like image 277
Alvin Avatar asked Dec 23 '15 13:12

Alvin


People also ask

Why do we use curly brackets?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.

What does curly braces mean in jQuery?

curly braces identify an Object like so: timObject = { property1 : "Hello", property2 : "MmmMMm", property3 : ["mmm", 2, 3, 6, "kkk"], method1 : function(){alert("Method had been called" + this. property1)} }; in jQuery they are used to provide an Object with options for your method.

Why do we use curly brackets in JavaScript?

Curly brackets { } is a code in javascript that groups altogether the code blocks or statements.. Its main purpose is to execute several code blocks or statements altogether..

Do you need curly brackets in JavaScript?

Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.


2 Answers

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);
like image 151
Anders Avatar answered Oct 11 '22 18:10

Anders


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.

like image 20
Guruprasad J Rao Avatar answered Oct 11 '22 18:10

Guruprasad J Rao