Paul Redmond
Paul Redmond

Reputation: 3296

jQuery - Combine variables and strings inside .css() method

How do you combine strings and variables as properties in the .css() method in jQuery?

I can easily do it if setting background-position-x and background-position-y but they aren't supported in Firefox & Opera.

function bgPos() {
    jq('element').each(function() {
        var bgPosX = 10;
        var bgPosY = 20;
        jq(this).css("background-position", "bgPosX + 'px', bgPosY + 'px'");
    });
}

Upvotes: 2

Views: 1596

Answers (3)

Dr. Elverhime
Dr. Elverhime

Reputation: 42

Get rid of the quotes around the variable:

jq(this).css("background-position", bgPosX + 'px' + bgPosY + 'px');

And get rid of the second comma...

Upvotes: -1

James Donnelly
James Donnelly

Reputation: 128856

The other answers here are incorrect as jQuery's css() method does not support 3 parameters and they will cause your bgPosY value to be ignored completely (and defaulted to 50%). I'm not actually sure how one of them received multiple upvotes...


You have two options here:

String Concatenation

You can concatenate your two variables into one string by using the + symbol:

.css({ backgroundPosition: bgPosX + "px " + byPosY + "px" })

Note how I've removed the comma between px and bgPosY and added a space to separate the two: "px ".

Setting Individual Properties

Alternatively you can just set the individual backgroundPositionX and backgroundPositionY properties:

(Edit: as Blazemonger has pointed out in this comment, these individual properties aren't supported in Firefox, so if you wish to support Firefox you should use the first option instead).

.css({
    backgroundPositionX: bgPosX,
    backgroundPositionY: bgPosY
})

Worth noting that I'm using object notation here rather than using strings, simply because I find this to be neater. You can stick to using "background-position" for the first example, and use "background-position-x" and "background-position-y" for the second example if you'd prefer.

Upvotes: 4

Mritunjay
Mritunjay

Reputation: 25892

.css doesn't accept 3 argument, so you can achieve what you want by giving an object.

say like bellow

jq(this).css({ backgroundPosition: bgPosX + "px " + byPosY + "px" });

Upvotes: 2

Related Questions