Create a Minimum Height Scrolling Effect Using jQuery

Posted by Ronald Huereca / May 10, 2019 /

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.

Posted in

Ronald Huereca

Ronald Huereca is the CEO of MediaRon LLC and enjoys WordPress plugin and theme development.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top