A little Pen I knocked together to demonstrate “CSS Animations triggered on scroll” to some of my students. The key part is the animated
class which actually starts the animation: it is only added once the element is in view.
Check out this Pen!
Note that the event handler is not debounced as we need to actually trigger the animations on actual scroll. Is partially optimised by removing the event handler once all elements are visible. Could be further optimised by throttling the event handler.
CSS animations are borrowed from http://glifo.uiparade.com/. Integration with animate.css of course also possible.
Consider donating.
I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!
UPDATE June 2016: For a project I’m building I need the animations to reverse when scrolling up. And so I build’eth.
Check out this Pen!
2 ‘easy’ optimisations I would suggest checking:
* don’t calculate offset and height in your event handler, cache it before your scroll loop runs.
* use requestAnimationFrame for scroll / resize events
It seems that this only works with an earlier version of jQuery (1.10.1).
Is there any update for more recent versions of jQuery?
It doesnt work at all. It just get triggered on loading and not on scroll or visible.
Any suggestions? ^^
The code examples have been updated to use the latest jQuery version (3.3.1 at the time of writing). Problem was that the
size()
method no longer existed, and got replaced with the.length
property.It doesn’t work with the most recent version of jQuery because .size() is deprecated.
Just replace
($animatables.size() == 0)
with
($animatables.length == 0)
Thanks Nate. I’ve updated the pens to use the latest jQuery version to prevent further confusion.
Just wanted to say thanks for posting this. It really added that extra detail to my portfolio that it was lacking. I also appreciate that you describe how to use it and what is happening in your comments in the code. It really helped out a lot and I learned some new stuff along the way.
Glad to have been of help 🙂
Hi Bramus, love the codePen thanks for this!
I have a large header with hero image, so the first item on a mobile device doesn’t appear until the user has scrolled down quite far. If I set this:
if (($animatable.offset().top + $animatable.height() – 1000) < offset) {
$animatable.removeClass('animatable').addClass('animated');
}
…notice the " – 1000" instead of your " – 20" in your codePen demo, then at least the first item appears on mobile the moment the page has loaded. But it messes with the rest of the items making all the items load once the page has loaded, sort of ruining the effect of it fading in up on scroll. How would I set a different offset for the first item but leave all other items the same?
Thanks!
how can it work with horizontal scroll?