Search code examples
jquerybackground-imageparallax

Background center parallax effect jumps to top


I am using the below code to provide a simple parallax effect to a background image. Ideally in the css I want the image to be centered (not top). However, as soon as I start scrolling the script jumps it to top and begins the effect. I cant work out if it's possible to alter the jquery so it begins with a centred image? can anyone help?

<div id="para" style="background-image: url('blah')" data-speed="8" data-type="background">
</div>

#para {
    height:500px;
    float:left;
    width:100%;
    background-size:100%;
    background-position: center center;
    background-repeat: no-repeat;
    background-attachemnt: fixed; 
}

//Parallax
$(document).ready(function() {
    if ($(window).width() > 1025) {
        // Cache the Window object
        $window = $(window);
        $('div[data-type="background"]').each(function() {
            var $bgobj = $(this);
            $(window).scroll(function() {
                var yPos = -($window.scrollTop() / $bgobj.data('speed'));
                var coords = '50% ' + yPos + 'px';
                $bgobj.css({
                    backgroundPosition: coords
                });
            });
        });
    }
});

Solution

  • You can't give background-position a percentage and pixels. It should be one or the other. Use percent units and then turn your $window.scrollTop() to a percentage as well. So multiply it by 100 and then divide by $window.height().

    //Parallax
    $(document).ready(function() {
    
        if ($(window).width() > 1025) {
            // Cache the Window object
            $window = $(window);
            $('div[data-type="background"]').each(function() {
                var $bgobj = $(this);
                $(window).scroll(function() {
                    var yPos = 50 - ($window.scrollTop() * 100 / $window.height() / $bgobj.data('speed'));
                    var coords = '50% ' + yPos + "%";
                    $bgobj.css({
                        backgroundPosition: coords
                    });
                });
            });
        }
    });
    

    your data-speed attribute needs to be lower too. I found 0.5 worked well.

    <div id="para" style="background-image: url('blah')" data-speed="0.5" data-type="background">