Felix
Felix

Reputation: 1583

Update multiple background-position on scroll using jQuery?

The parallax script doesn't update the css on $(window).scroll. It seems like you can not add multiple background-positions with jQuery?

Parallax scroll script:

<script>
var top_header = '';
$(document).ready(function(){
  top_header = $('header');
});
$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"left "+(st*.5)+"px,"});
});
</script>

CSS:

header {background-image: url(../images/1.png), url(../images/2.png);
        background-repeat: no-repeat, no-repeat;
        background-position: left, right; 
        height: 550px; width: 100%}

I've tried to update the css like this:

$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"left "+(st*.5)+"px,"+","+"right "+(st*.5)+"px,"});
});

This brakes the code and the header's background-position doesn't update on scroll as it should.

Any ideas appreciated.

Working example
Not working example

Upvotes: 1

Views: 1002

Answers (2)

Hamix
Hamix

Reputation: 1335

For multiple background image you should use the following structure:

background-image:url(1), url(2), ...;
background-repeat: no-repeat(1), no-repeat(2) , ...;
background-size: 50% 50% (1),50% 50%(2) ,...;
background-position: left center(1), right center(2), ....;

OR

background: 
   url(1) 600px 10px no-repeat,  /* On top,    like z-index: 4; */
   url(2) 10px 10px no-repeat,   /*            like z-index: 3; */
   url(3); 

Using JQuery

var top_header = '';
$(document).ready(function () {
    top_header = $('header');
});
$(window).scroll(function () {
    var st = $(window).scrollTop();
    top_header.css({
        'background-position': "left center," + "right " + (st * .5) + "px"
    });
});
$("#btnAdd").click(function () {
    var bg = $("header").css('background-image');
    $("header").css('background-image', bg + ', url("http://www.wired.com/wp-content/uploads/images_blogs/rawfile/2013/11/offset_RonnyRitschel_23712-1-660x660.jpg")');
});

In demo first click Add bg and scroll page to see result

DEMO

Upvotes: 0

Gildas.Tambo
Gildas.Tambo

Reputation: 22643

In css you set multiple background position like this:

 background-position: bottom right, left, right;

that means your code shall look some how like this

$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"left "+(st*.5)+"px," + "right "+(st*.5)+"px;"});
});

Upvotes: 1

Related Questions