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);Code language: JavaScript (javascript)

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.


Here’s some sample CSS I used:

.hero {
    background-image: url(;
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: scroll;
    background-size: cover;
    min-height: 800px;
    width: 100%;
}Code language: CSS (css)

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

Default Avatar
Choose an Avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Ronald Huereca
MediaRon - Ronald Huereca

Ronald created MediaRon in 2011 and has more than fifteen years of releasing free and paid WordPress plugins.

Quick Links

Say Hi