Last Updated: September 09, 2019
·
4.083K
· Ionut-Cristian Florescu

Basic plugin-free parallax scrolling

Everybody likes the trendy parallax scrolling effect... or so designers seem to believe nowadays.

Although most certainly overused, it can be a nice and useful tool sometimes. While there are great plugins out there (Matthew's parallax.js, jparallax, etc.), if you need something simple with just one scrolling image, and don't feel like including another 10k plugin, there's an easy way to do a basic effect with just a few lines of JavaScript/jQuery and CSS.

Assuming you want the effect applied on a <div class="hero"> with a background image higher than the element height and an initial background-position: center bottom, you can do something like this:

var $hero = $('.hero'),
    heroBottom = $hero.offset().top + $hero.height();

$win.on('scroll', function() {
  var scrollTop = $win.scrollTop(),
      yPosPercent = (1 - Math.min(1, scrollTop / heroBottom)) * 100;

  $hero.css('background-position', 'center ' + yPosPercent + '%');
});

Quick, plugin-free, parallax scrolling

You can see it live here on home, services and portfolio pages.

2 Responses
Add your response

Is there a way to smooth with an animation. The transition is very fast and the photo just changes (no transition).

over 1 year ago ·

@dansabin - haven't got much time to experiment, but adding a CSS transition: background-position 1s on the <div class="hero"> element might work.

But the whole adjustment + transition might be a bit CPU/GPU intensive, especially for mobile devices, which is why the scroll event handler should probably be debounced.

If I remember correctly, I've noticed the animation on interiordelight.ro was initially a bit jerky on Android/iOS, and I think I've tried doing just that for mobile devices...

over 1 year ago ·