Search code examples
jquerybackgroundparallax

jQuery - Parallax Effect - Change Background Position to "Center Center"


I've implemented the below jQuery parallax effect into my website (taken from http://www.brandaiddesignco.com/insights/parallax-scrolling-made-easy/):

var top_header = '';
$(document).ready(function(){
  top_header = $('.header-container');
});
$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"center "+(st*.5)+"px"});
});

It works great, and all I needed to do was simply applying it to the class containing the background. However, the starting position of the background image is top center and I would like to change it to center center. I have tried changing the code to the following, which made the plugin stop working:

top_header.css({'background-position':"center center"+(st*.5)+"px"});

Any suggestions?

Thanks!


Solution

  • Figured it out... got it working with CSS calc() :

    $(document).ready(function(){
    
    var top_header = $('.header-container');
    top_header.css({'background-position':'center center'}); // better use CSS
    
    $(window).scroll(function () {
    var st = $(this).scrollTop();
    top_header.css({'background-position':'center calc(50% + '+(st*.5)+'px)'});
    });
    });
    

    http://codepen.io/anon/pen/qEgQzK?editors=001

    Original answer was edited.