DEV Community

Building a Headroom-Style Header in Svelte

Thomas Collardeau on October 02, 2019

Let us build a headroom-style header in Svelte! Our objective in this blog post is to create a header that slides up (and out-of-view) when the use...
Collapse
 
vekzdran profile image
Vedran Mandić

Lovely share and a fun teaching project. Really love seeing Svelte breaking through!

Typo maybe: We would have to this when the component, seems like it is missing a word or I am having a hard time understanding what is "this" (the usual issue in JS)?

Collapse
 
collardeau profile image
Thomas Collardeau

"we would have to DO this...."

Fixed it. Thanks.

Collapse
 
nmrshll profile image
Nicolas Marshall • Edited

sorry: "this" is not a function

Collapse
 
wlockiv profile image
wlockiv

Thank you for this - I just used it for my own web app!

May I make a recommendation? Some browsers (Safari or Browsers on iOS) will let you scroll "above" 0, into the negative numbers. This will cause the header to collapse after the user scrolls to the top. I would recommend changing the following line in your changeHeaderClass:

lastY = y;

to:

lastY = y >= 0 ? y : 0;

This will prevent the lastY value from becoming negative.

Or, instead - you can short-circuit the entire function by adding the following to the first line of it:

if (y < 0) return 'pin';

Which would technically be more efficient I guess 🙃

Collapse
 
collardeau profile image
Thomas Collardeau

I built a svelte-headroom component if anybody reading this is interested:

github.com/collardeau/svelte-headroom

Collapse
 
thompcd profile image
Corey Thompson

You did a little extra in your code sandbox it looks like. I really like the hysteresis effect with the added tolerance. I feel like that minor detail added the polish that makes it feel great. :)