Creating Parallax Effect using JavaScript

What is Parallax Effect?

Parallax effect is a trend in web designing which involves moving of background image slower than the actual scrolling of the page or just keeping it the fixed to its position i.e. not moving at all. Parallax Effect in a page creates an awesome illusion by giving the content a 3D effect while scrolling.

Parallax Effect is used by many bloggers and in many company websites, as it gives the user/visitor a soothing feel while scrolling, giving a website a fresh, stylish and modern look and feel.

Here in this post I will be showing two simple ways of Parallax Effect, one which only requires CSS and another requires little bit of JavaScript.

Parallax Effect (Image position Fixed | CSS Only)

In this parallax effect the remains fixed to its position and don't gets scrolled at all. It is one of the most easiest effect to use, even I'm using this effect in my website homepage header. Take a look

Here is an example

<style> header { background-image:url('Image URL'); /* URL of your background Image */ background-attachment: fixed; /* forcing the background to be fixed*/ background-size: cover; background-repeat: no-repeat; } </style>

See the Pen Parallax effect (Image Fixed | CSS Only) by bishal-biswas (@bishal-biswas) on CodePen.

Benefits of using this Parallax Effect
  • Its very easy to implement.
  • Works in all devices(Mobile, tablets) as rendering is not an issue because image is fixed.

Parallax Effect (JavaScript Required)

In this parallax effect the background is made to scroll slower than the actual scrolling. This is done by forcing the Y-axis position values of the image to be less than the actual window page Y-axis offset.

Here is an example

<script> window.addEventListener('scroll' , function(){ const BgImg = document.querySelector('header img'); let WinPos = window.pageYOffset; BgImg.style.transform = "translateY(" + WinPos * .35 + "px)"; }); </script>

See the Pen Simple Parallax Scrolling Effect by bishal-biswas (@bishal-biswas) on CodePen.

Problems with this Parallax Effect
  • Background Image scrolling is not smooth, giving a flickery effect.

(Please do comment, If you can help me remove the flicker effect.)

Checkout the Other ways of implementing Parallax Effect

Comments