Deep dive into how IntersectionObserver works
This is a delightfully nerdy exploration of how IntersectionObserver works, its quirks and caveats, and how it can be used to create a JavaScript position: sticky
event as a bonus.
This is a delightfully nerdy exploration of how IntersectionObserver works, its quirks and caveats, and how it can be used to create a JavaScript position: sticky
event as a bonus.
I made a little tweak to The Session today. The navigation bar across the top is “sticky” now—it doesn’t scroll with the rest of the content.
I made sure that the stickiness only kicks in if the screen is both wide and tall enough to warrant it. Vertical media queries are your friend!
But it’s not enough to just put some
position: fixed
CSS inside a media query. There are some knock-on effects that I needed to mitigate.I use the space bar to paginate through long pages. It drives me nuts when sites with sticky headers don’t accommodate this. I made use of Tim Murtaugh’s sticky pagination fixer. It makes sure that page-jumping with the keyboard (using the space bar or page down) still works. I remember when I linked to this script two years ago, thinking “I bet this will come in handy one day.” Past me was right!
The other “gotcha!” with having a sticky header is making sure that in-page anchors still work. Nicolas Gallagher covers the options for this in a post called Jump links and viewport positioning. Here’s the CSS I ended up using:
:target:before {
content: '';
display: block;
height: 3em;
margin: -3em 0 0;
}
I also needed to check any of my existing JavaScript to see if I was using
scrollTo
anywhere, and adjust the calculations to account for the newly-sticky header.Anyway, just a few things to consider if you’re going to make a navigational element “sticky”:
- Use
min-height
in your media query,- Take care of keyboard-initiated page scrolling,
- Adjust the positioning of in-page links.