GSAP Image with parallax effect

Register gutenberg block style, in block-styles.js

wp.domReady( () => {
	wp.blocks.registerBlockStyle( 
		'core/image', {
			name: 'with-parallax',
			label: 'With Parallax',
		}
	);
} );

Add GSAP in gsap.js

gsap.registerPlugin(ScrollTrigger);
// Parallax Images
function initImageParallax() {
  // select all sections with a parallax image
  gsap.utils.toArray('.is-style-with-parallax').forEach(section => {
      // get the image
      const image = section.querySelector('img');
      // create tween for the image
      gsap.to(image, {
          // increase this to have more movement and match the SCSS
          yPercent: 20,
          ease: 'none',
          scrollTrigger: {
              trigger: section,
              start: 'top bottom',
              scrub: true
          }
      });
  });
}
window.addEventListener('load', function(){
    initImageParallax();
});

Add the SCSS in _image-styles.scss

.is-style-with-parallax {
	&.wp-block-image {
	    // this is the default padding-bottom for a ratio 2:1 image
		padding-bottom: 50%;
		position: relative;
		overflow: hidden;
	}
	img {
		position: absolute;
		object-fit: cover;
		object-position: 50% 50%;
		opacity: 1;
		max-width: none;
		// increase the image size to allow for the movement behind the container mask
		// SHOULD line up with GSAP yPercent 
		left: -10%;
		width: 120%;
		height: 120%;
		top: -20%;
	}
}

some jquery to fix the padding on containers for anything that is not a 1:2 ratio image

    $( ".is-style-with-parallax img" ).each(function( index ) {
      var width = $(this).attr('width');
      var height = $(this).attr('height');
      var ratio = height / width * 100;
      $(this).parent().css("padding-bottom", ratio + "%");
    });

Search the site


Address

123 Main Street
Town
City
P05T C0D3

Tel: 01234 567 899

Mob: 01234 567 899

Email: ben@gomopress.com


Copyright 2023. Blah blah blah Company Limited