Create a Minimum Height Scrolling Effect Using jQuery

timelapse photography of train passing on track
Photo by William Daigneault on Unsplash

I was recently tasked with creating a scrolling effect that reduced the size of the hero as the user scrolled down.

Here’s the JavaScript and CSS I used, and I will link to the JSFiddle at the end of the post for a demonstration.

The JavaScript

var hero_offset = $( '.hero' ).offset().top; var min_height = $( '.hero' ).css( 'min-height' ).replace('px', '' ); window.addEventListener('scroll', function( e ) { if ( window.pageYOffset < hero_offset ) return; var new_height = Math.ceil( min_height - ( window.pageYOffset - hero_offset ) ); if( new_height < 0 ) return; $( '.hero' ).css( 'min-height', new_height + 'px' ); }, false);

The JS just grabs the offset of the hero and the min-height, and calculates a new min-height as the window scroll down the hero.

The CSS

Here’s some sample CSS I used:

.hero { background-image: url(https://mediaron.com/wp-content/uploads/2019/05/becca-tapert-1561341-unsplash.jpg); background-repeat: no-repeat; background-position: center center; background-attachment: scroll; background-size: cover; min-height: 800px; width: 100%; }

And the Demo

View the JSFiddle.

Ronald Huereca
Ronald Huereca

Ronald Huereca

Ronald has been part of the WordPress community since 2006, starting off writing and eventually diving into WordPress plugin development and writing tutorials and opinionated pieces.

No stranger to controversy and opinionated takes on tough topics, Ronald writes honestly when he covers a topic.

Leave a Comment