Four Kitchens: Creating depth and motion: A step-by-step guide to parallax

Image removed.

Mari Núñez

Frontend Engineer

Mari is a high-achieving Drupal frontend developer who has shown great proficiency in tackling complex frontend problems.

January 1, 1970

Crafting a visually engaging website isn’t just about eye-catching colors and typography — today it’s also about creating immersive experiences that captivate users as they scroll. One of the most compelling ways to achieve this is by using a parallax effect, where elements move at different speeds to create a sense of depth and motion.

With a thoughtful approach and some JavaScript, you can seamlessly add this effect to your site, enhancing storytelling and making your pages more dynamic.

This post will guide you through the process of integrating a custom parallax effect into your site. Whether building a feature-rich landing page or enhancing storytelling elements, this technique can bring your site to life. Let’s begin.

Building our component

Our example site was built in Drupal, but the overall concept would be the same in any CMS. First, we will need to build a component that has all the necessary fields that we want to display in our parallax. In this example, we will use Paragraph types and have two kinds of slides: one with an image and another without an image.

Parallax image slide

This slide will let us add an image, a title, and the caption or information we want to tell about that specific slide, the alignment of the information (left, center, or right), and an option if we want to hide the credit of the image or show it.

Image removed.
Parallax blank slide

This slide is similar to the previous one, but there are key differences. This one won’t include an image and anything else related to the image, and we allow a lot more text formatting on blank slides. This means that we can have the text on a blank slide take up much more of the available space without worrying about color contrast issues with advanced text formatting.

Image removed.

Once both paragraphs have been created, let’s create a ‘Parallax Slideshow’ paragraph that will only have a field that references the previous paragraphs created.

Image removed.

Connecting our component to the custom theme

Once our component is ready, the next step is to integrate it into our custom theme. In this example, we’re using Emulsify, our design system, as our custom theme, to ensure a consistent and modular approach to theming.

First, we will have our paragraph--parallax-slideshow.html.twig that will include a parallax-slideshow.twig, which has a JavaScript library called parallax-slideshow that is in charge of all logic to make our parallax effect work, and also some required styles.

{{ attach_library('your_theme/parallax-slideshow') }} {% set drupal = true %} {% include "@organisms/parallax-slideshow/parallax-slideshow.twig" with { 'slideshow_id': paragraph.id.0.value, 'slides': content.field_slide_items|render } %}

Here’s what our parallax-slideshow.twig looks like. Notice the empty <div class=””parallax-slideshow__image-wrapper””></div>. This is where the slide images will be rendered and where the fade-in and fade-out effects between images will occur.

{% set classes = [ paragraph.bundle|clean_class, "parallax-slideshow", ] %} <div{{ attributes.addClass(classes) }} data-id="{{ slideshow_id }}"> <div class="parallax-slideshow__wrapper"> <div class="parallax-slideshow__image-wrapper"></div> {{ slides }} </div> </div>

Then, we will have a paragraph--parallax-image-slide.html.twig and a paragraph--parallax-blank-slide.html.twig. Both files include a parallax-slide.twig, which is a molecule in the design system that organizes the content of each slide and adds all the needed styles. They are almost identical — the only difference being that the blank-slide will not pass the slide image to the parallax-slide.twig file.

{% include "@molecules/parallax-slide/parallax-slide.twig" with { 'slide_id': paragraph.id.0.value, 'slide_img': content.field_image|render, 'slide_title': paragraph.field_component_title.0.value, 'slide_caption': content.field_caption|render, 'slide_caption_alignment': paragraph.field_caption_alignment.0.value, 'slide_hide_credit': paragraph.field_hide_credit.0.value, 'slide_type': paragraph.type.0.value.target_id, } %}

Here’s what our parallax-slide.twig looks like:

{% set classes = [ 'parallax-slide', slide_caption_alignment ? 'parallax-slide--caption-' ~ slide_caption_alignment|lower : '', slide_type ? 'parallax-slide--' ~ slide_type|replace({'_': '-'}) : '', ] %} <div {{ attributes.addClass(classes) }} slide-data-id="{{ slide_id }}"> <div class="parallax-slide__info-wrapper"> <div class="parallax-slide__info-inner-wrapper full-width"> {% if slide_title %} <div class="parallax-slide__title-wrapper"> <h1 class="parallax-slide__title">{{ slide_title }}</h1> </div> {% endif %} {% if slide_caption %} <div class="parallax-slide__caption">{{ slide_caption }}</div> {% endif %} </div> </div> </div>

Preloading parallax slideshow data

To prevent a visible delay between slides, the component needs to preload the first two images on page load. As the user begins scrolling, additional images are loaded dynamically in the background. This ensures a seamless transition between slides without noticeable lag and enhances the overall user experience.

We need to pass structured data from the backend to JavaScript. Below is a function that loads the data and attaches it to drupalSettings for use in a theme.

function your_theme_preprocess_paragraph_parallax_slideshow(&$variables) { $paragraph = $variables['paragraph']; $pid = $paragraph->id(); $lazy_load_data[$pid] = []; if ($paragraph->hasField('field_slide_items')) { $slide_items_ref = $paragraph->get('field_slide_items'); $slide_items = $slide_items_ref->referencedEntities(); foreach ($slide_items as $slide_id => $slide) { // Initial setup of array. $lazy_load_data[$pid][$slide_id] = [ 'id' => NULL, 'image' => NULL, ]; // ID. if ($slide->hasField('id') && !$slide->get('id')->isEmpty()) { $lazy_load_data[$pid][$slide_id]['id'] = $slide->get('id')->first()->getValue(); } // Responsive image markup. if ($slide->hasField('field_image') && !$slide->get('field_image')->isEmpty()) { $lazy_load_data[$pid][$slide_id]['image'] = _your_theme_get_rendered_slide_image($slide); } } } // Attach to JS JSON object to read in theme. $variables['#attached']['drupalSettings']['yourTheme']['parallaxSlideshowData'] = $lazy_load_data; $variables['#attached']['library'][] = 'your_theme/parallax-slideshow'; } function your_theme_get_rendered_slide_image($slide) { if ($slide->hasField('field_image') && !$slide->get('field_image')->isEmpty()) { $image_view = $slide->field_image->view('default'); $rendered_image = \Drupal::service('renderer')->render($image_view); return $rendered_image; } return NULL; }

Once the data is attached to drupalSettings in our JavaScript file, we can access parallaxSlideshowData to dynamically load images and control the parallax effect.

JavaScript implementation of the parallax slideshow

Below is a breakdown of how the JavaScript file works to bring the parallax slideshow to life.

Drupal.behaviors.parallaxSlideshow = { attach: function (context) { const parallaxSlideshowData = drupalSettings.yourTheme.parallaxSlideshowData; if (!parallaxSlideshowData) return; const slideshows = once('parallax-slideshow', '.parallax-slideshow', context); slideshows.forEach((slideshow) => { const loadedSlideIds = new Set(); const loadedImages = new Set(); initializeParallaxSlideshow(slideshow, parallaxSlideshowData, loadedSlideIds, loadedImages); }); }, };

Let’s start by retrieving the slideshow data from drupalSettings and ensuring the script only runs once per slideshow element. The function initializeParallaxSlideshow is responsible for setting up and managing the parallax slideshow experience by initializing each slideshow. By tracking which slides have been loaded, we prevent redundant loading:

const slideshowDataID = slideshow.getAttribute('data-id'); const slideshowData = parallaxSlideshowData[slideshowDataID]; if (!slideshowData) return;

Then, it calls a preloadSlides function, which likely preloads images or other resources for the first two slides to prevent a visible delay between slides.

function preloadSlides(slideshowData, slideshow, loadedSlideIds, loadedImages){ slideshowData.slice(0, 2).forEach((slideData, index) => { // Check if the slide has already been added if (loadedSlideIds.has(slideData.id)) return; // Mark the slide as loaded loadedSlideIds.add(slideData.id); if (slideData.image !== null) { createImageDiv(slideData.id, slideData.image, slideshow, loadedImages, index === 0); } }); }

Next, it calls a createImageDiv helper function that is responsible for creating and managing an image element within the parallax slideshow.

function createImageDiv(slideID, slideImage, slideshow, loadedImages, firstImage = false) { const imgDiv = document.createElement('div'); imgDiv.className = 'parallax-slideshow__image'; imgDiv.innerHTML = slideImage; if (firstImage) { const image = imgDiv.querySelector('img'); image.addEventListener('load', () => { const slideshowOverlay = slideshow.querySelector( '.parallax-slideshow__overlay', ); const slideshowWrapper = slideshow.querySelector( '.parallax-slideshow__wrapper', ); if (slideshowOverlay) { slideshowOverlay.classList.add('fade-out'); setTimeout(() => { document.body.style.overflow = ''; slideshowWrapper.removeChild(slideshowOverlay); }, 1000); } }); } // Add a custom attribute for the slide ID imgDiv.setAttribute('data-slide-image-id', slideID); loadedImages.add({ id: slideID, image: imgDiv, }); }

The reason why we check if there is a firstImage is that we want the initial slide to fade in from black when it’s fully loaded. Once the image loads, it finds the overlay and the slideshow wrapper, fades out the overlay, removes the overlay, and re-enables scrolling.

Let’s go back to the initializeParallaxSlideshow. After the preloadSlides function there’s a scroll event listener for the parallax effect that listens for scroll events to update the slideshow’s image position dynamically.

The idea is to let the image wrapper take the whole height of the viewport, but since there can be components before or after the parallax slideshow, at some point it is necessary to change the position of the image wrapper, to let the user scroll and interact with other components.

window.addEventListener('scroll', () => { const windowHeight = window.innerHeight; const top = slideshow.getBoundingClientRect().top; const bottom = slideshow.getBoundingClientRect().bottom; const slideshowImageWrapper = slideshow.querySelector( '.parallax-slideshow__image-wrapper', ); if (top < 0 && bottom > windowHeight) { slideshowImageWrapper.style.position = 'fixed'; slideshowImageWrapper.style.top = 0; } else { slideshowImageWrapper.style.position = 'absolute'; if (windowHeight > bottom) { slideshowImageWrapper.style.top = 'unset'; slideshowImageWrapper.style.bottom = 0; } if (windowHeight < top) { slideshowImageWrapper.style.top = 0; slideshowImageWrapper.style.bottom = 'unset'; } } });

The following logic is to set a scroll hijacking if the parallax slideshow is the first component of the page and if the first slide is an image.

// Check if slideshow is within a parent of .content-top const isContentTopParent = slideshow.closest('.content-top') !== null; // Get the first slide and check if it has the class `parallax-slide--parallax-image-slide` const firstSlide = slideshow.querySelector('.parallax-slide'); const isFirstSlideParallaxImageSlide = firstSlide && firstSlide.classList.contains('parallax-slide--parallax-image-slide'); // Lock scroll if .content-top is present and the first slide is of type image if (isContentTopParent && isFirstSlideParallaxImageSlide) { const overlay = document.createElement('div'); overlay.className = 'parallax-slideshow__overlay'; slideshow .querySelector('.parallax-slideshow__wrapper') .appendChild(overlay); document.body.style.overflow = 'hidden'; }

Then, there’s a piece of code that iterates through all slides in the slideshow and calls the initializeSlideObserver() function on each slide.

const slides = slideshow.querySelectorAll('.parallax-slide'); slides.forEach((slide, index) => { const infoInnerWrapper = slide.querySelector( '.parallax-slide__info-inner-wrapper', ); initializeSlideObserver(slideshow, infoInnerWrapper, slide, slideshowData, loadedSlideIds, loadedImages); // Add classes if first image is an slide if (index === 0) { slide.classList.add('initial-slide'); if (isFirstSlideParallaxImageSlide) { slide.classList.add('initial-slide-image'); } } });

Now let’s take a look at the initializeSlideObserver() function — the one that is responsible for setting up an Intersection Observer to track when a slide enters the viewport and dynamically updates the slideshow’s displayed image accordingly. It ensures that the slideshow loads the next image only when needed, preventing unnecessary rendering and improving performance.

// Initialize Intersection Observer for Slides function initializeSlideObserver(slideshow, infoInnerWrapper, slide, slideshowData, loadedSlideIds, loadedImages) { // Watches when infoInnerWrapper enters or exits the viewport, // and triggers a callback whenever visibility changes const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { const slideshowWrapper = slideshow.querySelector( '.parallax-slideshow__wrapper', ); const slideshowImageWrapper = slideshowWrapper.querySelector( '.parallax-slideshow__image-wrapper', ); const slideID = slide.getAttribute('slide-data-id'); const slideImage = Array.from(loadedImages).find( (loadedImage) => loadedImage.id === slideID, ); const { isIntersecting } = entry; // Checks if the slide currently intersects the root if (isIntersecting) { const parent = slide.parentNode; const slides = Array.from( parent.querySelectorAll('.parallax-slide'), ); const index = slides.indexOf(slide); if (index !== 0) { // If not first slide, call the function to preload the next slide in advance. loadNextSlide(slideshowData, index, loadedSlideIds, loadedImages); } // Check if there is an existing image const previousImage = slideshowImageWrapper.querySelector( '.parallax-slideshow__image', ); if (slideImage) { slideImage.image.classList.add('fade-in'); slideshowImageWrapper.appendChild(slideImage.image); // If an existing image is found, remove fade-in class and remove it after a delay if (previousImage) { const previosImageID = previousImage.getAttribute( 'data-slide-image-id', ); if (previosImageID !== slideID) { setTimeout(() => { previousImage.classList.add('fade-out'); // Add fade-out class previousImage.classList.remove('fade-in'); // Remove fade-in class previousImage.classList.remove('fade-out'); // Remove fade-out class slideshowImageWrapper.removeChild(previousImage); }, 500); } } } else { if (previousImage) { const previosImageID = previousImage.getAttribute( 'data-slide-image-id', ); if (previosImageID !== slideID) { previousImage.classList.add('fade-out'); // Add fade-out class setTimeout(() => { previousImage.classList.remove('fade-out'); slideshowImageWrapper.removeChild(previousImage); }, 500); } } } } }); }, { // The callback triggers when at least 5% of infoInnerWrapper is visible. threshold: 0.05, }, ); observer.observe(infoInnerWrapper); }

Last but not least, there’s the loadNextSlide function that is responsible for preloading the next slide’s image to ensure a smooth transition when the user scrolls. This prevents unnecessary reloading of already loaded images. This function is very similar to the preloadSlides function.

function loadNextSlide(slideshowData, currentIndex, loadedSlideIds, loadedImages) { if (currentIndex + 1 < slideshowData.length) { const nextSlideData = slideshowData[currentIndex + 1]; // Check if the slide has already been added if (loadedSlideIds.has(nextSlideData.id)) return; // Mark the slide as loaded loadedSlideIds.add(nextSlideData.id); if (nextSlideData.image !== null) { createImageDiv(nextSlideData.id, nextSlideData.image, null, loadedImages); } } }

With these functions in place — handling image creation, slide observation, and preloading — you now have a dynamic and efficient parallax slideshow that seamlessly transitions between images as users scroll. By leveraging the Intersection Observer API, preloading logic, and smooth fade effects, the slideshow ensures a visually engaging experience without unnecessary performance overhead.

Once you’ve added the necessary styles to control positioning, animations, and transitions, your parallax slideshow should be fully functional across your site. This approach not only enhances the storytelling aspect of your content, but also keeps interactions smooth and lightweight.

Now, all that’s left is to fine-tune the visuals to match your design, and you’re set to create an immersive scrolling experience! Image removed.

The post Creating depth and motion: A step-by-step guide to parallax appeared first on Four Kitchens.

PubDate

Tags