Gallery · 09 of 33

Parallax Scroll

Image moves slower than scroll

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<!-- Put this partway down a scrollable page so it can move -->
<div class="parallax-container" id="parallaxContainer">
  <img src="https://picsum.photos/id/54/800/900" alt="Tall Building" id="parallaxImg">
</div>

CSS

.parallax-container {
  width: 400px;
  aspect-ratio: 4 / 3;
  overflow: hidden;
  border-radius: 12px;
}

/* Image is taller than its frame so it has room to slide */
.parallax-container img {
  width: 100%;
  height: 120%;
  object-fit: cover;
  display: block;
  will-change: transform;
}

JavaScript

var container = document.getElementById('parallaxContainer');
var img = document.getElementById('parallaxImg');
var RANGE = 80; // total px of travel across the viewport

var ticking = false;

function update() {
  ticking = false;
  var rect = container.getBoundingClientRect();
  var viewHeight = window.innerHeight;
  if (rect.top < viewHeight && rect.bottom > 0) {
    // 0 when entering at the bottom, 1 when leaving at the top
    var progress = (viewHeight - rect.top) / (viewHeight + rect.height);
    var y = (progress - 0.5) * RANGE;
    img.style.transform = 'translateY(' + y + 'px)';
  }
}

function onScroll() {
  if (!ticking) {
    ticking = true;
    requestAnimationFrame(update);
  }
}

window.addEventListener('scroll', onScroll, { passive: true });
update();