I recently got inspired by this article, where elements became visible (with nice and nifty animations) when the user started scrolling. Now I wanted to implement something like this in a project I’m currently working on, and a purist as I am I wanted to do this with nothing more than CSS3 transitions. The idea is actually quite simple: just toggle a class on the <body> -tag of your page, and let CSS do the rest.
Switching the class
I didn’t wanted to include a whole library for this and I also didn’t care that much about being backward compatible to older (read: Internet Explorer) browsers. So I just came up with this small and simple way of doing this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/** * Real tiny JS function to check if the user has scrolled or not * The body class can be used with CSS transitions for some funky * effects while scrolling. * * @author Giel Berkers (https://gielberkers.com) * * @constructor */ var ScrollDetector = function() { "use strict"; window.addEventListener( 'scroll', function() { if( window.scrollY > 0) { document.body.classList.add( 'scrolled' ); } else { document.body.classList.remove( 'scrolled' ); } }); }; new ScrollDetector(); |
That’s it! That’s the only piece of code that toggles the scrolled -class on my <body> -tag.
Animate it with CSS
When it comes to the animating part, we let SCSS do the magic for us. Be creative! Animate with margins, opacity, colors, you name it! Here’s a little SCSS to set you up:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
body { background: url('path/to/image.jpg'); background-attachment: fixed; background-position: center center; background-size: cover; padding-top: 100px; transition: all 1s; header { background: black; color: white; transition: all 1s; } .content { margin-top: 200px; // Don't show content: opacity: 0; pointer-events: none; } &.scrolled { // Animate padding-top: padding-top: 0; header { // Invert colors on header: color: black; background: white; } .content { // Make content visible: opacity: 1; pointer-events: auto; } } } |
This is of course very basic, but you could stretch this as far as you want. I’ve created a little demo on CodePen that shows a single example of what can be done. Just open it, scroll down and see the magic happen.
Visitors give this article an average rating of 4.3 out of 5.
How would you rate this article?
★ ★ ★ ★ ★