
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.
The CSS
Here’s some sample CSS I used:
.hero {
background-image: url(https://eoo7ycy6qqi.exactdn.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%;
}
Code language: CSS (css)