user3773890
user3773890

Reputation: 161

background image that moves when you scroll down the page

I keep seeing websites with a background image that subtly moves when you scroll down. This is a really nice effect but I'm not sure how to do this? I'm am experienced with html, css and jquery but this is something I haven't done before!

I have a simple jsfiddle below but I need some help please!

Many thanks,

http://jsfiddle.net/def2y2yt/

Code snippet - more available using the jsfiddle link

.background {
    background-image: url(example.pjg);
    background-repeat: no-repeat;
    height: 600px;
    width: 100%;
}

Upvotes: 13

Views: 56091

Answers (3)

Sam
Sam

Reputation: 471

Like TylerH said, it's called Parallax. You can see an example here.

Using JavaScript:

var velocity = 0.5;

function update(){ 
var pos = $(window).scrollTop(); 
$('.container').each(function() { 
    var $element = $(this);
    // subtract some from the height b/c of the padding
    var height = $element.height()-18;
    $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) +  'px'); 
   }); 
   };

 $(window).bind('scroll', update);

Upvotes: 22

Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13882

The best library for that is Stellarjs

Take a look at the example here

http://markdalgleish.com/projects/stellar.js/demos/backgrounds.html

Upvotes: 2

Nathan Peixoto
Nathan Peixoto

Reputation: 328

Or you could use this simple CSS property which I made a blog post about: http://nathanpeixoto.fr/blog/article8/web-un-one-page-presque-sans-javascript (French only, sorry).

Let's say this is your HTML:

<div class="background_container">

</div>
<style>
.background_container{
  background-image: url("XXX");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed; /* <= This one */
}
</style>

Upvotes: 21

Related Questions