Doro Doro - 2 months ago 13
CSS Question

JS (CSS) dynamic background image moving

I made up a little script that makes a photo background to scroll up/button in same time with page scrolling. The problem is that the background image is scrolling after the page was scrolling (it have a delay).

Question: How may I make to move background image with page scrolling like in this example http://shapebootstrap.net/item/1524936-unika-responsive-one-page-html5-template/live-demo ?

I made a plnkr with my code: https://plnkr.co/edit/e6OCUF4sXSA80Pi6XANj?p=preview

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<!-- version 0.6.1.0 -->
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" type="text/css" href="app.css"></link>
</head>
<body>
<div id="add-outer-container"></div>
<div style="height: 1500px; color: green;"></div>
</body>
</html>


CSS:

html, body {
height:100%;
margin:0;
padding:0;
background-color:gray;
}

#add-outer-container {
width:100%;
height:500px;
background: #fff url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat fixed 0% 0%;
overflow: hidden;
color: white;
border: 1px solid red;
}


JS:

var bgScroll = function (lastScrollTop, elem) {
lastScrollTop = $(window).scrollTop();
$(elem).css('transition', 'all .5s');
$(elem).css('background-position','0% '+parseInt(-lastScrollTop/2)+'px');
console.log('lastScrollTop = ' + lastScrollTop);
};
$(window).load(function() {
var lastST = 0;
var homeElem = '#add-outer-container';
$(window).on("scroll", function() {
bgScroll(lastST, homeElem);
});
});

Answer

What your are looking for is called parallax effect. There are several libraries which can help you (http://pixelcog.github.io/parallax.js/ for instance). But the simplest solution could something like this:

// Handle the window scroll event
$(window).scroll(function () {
    // Store the distance scrolled
    var scrolled = $(window).scrollTop() + 1;

    // Set the scroll speed
    var scrollSpeed = 0.3;
    
    // Update the background position
    $("#add-outer-container").css('background-position', '0' + -(scrolled * scrollSpeed) + 'px');
});
body {
    min-height:3000px;
}

#add-outer-container {
    background:url(http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg) no-repeat  fixed;
    width:100%;
    height:500px;
    margin:0 auto;
    border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="add-outer-container"></div>