Search code examples
jquerycssbackground-positionbackground-image

jquery to change css background position on multiple backgrounds


I am trying through jquery to change the background images position of an element depending on resolution. The code:

var pwwidth = $(window).width();
var pwheight =  $(window).height();
var bg1posx = pwwidth - $('h1.portofolio').width();
var bg1posy = pwheight - $('.footer').height();
var bg2posx = $('.leftporto').width() - (pwwidth * 0.05);
var bg2posy = ($('h1.portofolio').height() / 2 ) + $('h1.portofolio').css('margin-top').replace('px', '');
$('#content4').css('background-position', bg1posx+'px' bg1posy+'px', bg2posx+'px' bg2posy+'px');

In CSS you change multiple backgrounds of an element like this:

background-position: 100px 200px , 300px 400px;
background-position: 10% 20% , 30% 40%;

I cannot define it to change with jquery as this will not work

$('#content4').css('background-position', bg1posx+'px' bg1posy+'px', bg2posx+'px' bg2posy+'px');

Solution

  • You have a syntax error (improper concatenation of strings) in your code:

    Bad:

    $('#content4').css('background-position', bg1posx+'px' bg1posy+'px', bg2posx+'px' bg2posy+'px');

    Good:

    $('#content4').css('background-position', bg1posx+'px '+bg1posy+'px, '+bg2posx+'px '+bg2posy+'px');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​