Monday 15 February 2016

Parallax animation with slow background scrolling

To have the parallax animation with slow background scrolling, we need just a simple Javascript and CSS. We need to fix the background and position it.

Please refer the below CSS
body {
  background-image: url(images/bg.jpg); 
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: 0 0;}
Here we have fixed the background as
background-attachment: fixed
also set the background-position as
background-position: 0 0;
So we can change this property on scroll of the page.

The CSS is done. Now comes the JS. Nothing much we just need to add an event for scroll, and get the pageYOffset.
window.addEventListener('scroll', doParallax);
function doParallax(){
    var positionY = window.pageYOffset/2;
    document.body.style.backgroundPosition = "0 -" + positionY + "px";
}
Here we are just changing background position y value on scroll of the page. We are just dividing the pageYOffset of window by 2, i.e., decreasing the scrolling speed of background image by 50%. That's it. Hope this helps someone. Enjoy :)

Please have a look at the DEMO here