I wrote a simple JavaScript function to animate objects on my webpage to fade and slide in from the bottom of the screen when the user scrolls them into view. I did this by using JavaScript to add and remove a CSS class that animates the element to every element with the showOnScroll class.

Example element:

<content-card class="animated showOnScroll" data="[[item]]"></content-card>

JavaScript function:

window.onscroll = function(e) {
  var toShow =  document.querySelectorAll('.showOnScroll');
  for(var i = 0; i < toShow.length; i++) {
    if(window.innerHeight - toShow[i].getBoundingClientRect().top - 100 > 0) {
    } else {

The fadeInUp and fadeInDown classes use CSS to animate the elements. See a work in progress here (may not work on mobile). The app is written using Polymer.

I'm mostly concerned about performance—if I have around 50 of these elements on a page, can that noticeably impact most browsers? If so, I have a couple of ideas to optimize already:

  • Remove the showOnScroll class once an element has been scrolled in (only animate each element once instead of fading in and out)
  • Append elements to the DOM as the user scrolls down
  • Only run the loop if the user scrolls at least 50px

Are these going in the right direction? Is there anything else I should consider?

  • 1
    \$\begingroup\$ Short answer: attaching things to the scroll event can be a recipe for disaster. (Especially when touching the DOM.) You should look into throttling your function (and also move things like var toShow = document.querySelectorAll('.showOnScroll'); outside the scroll listener). \$\endgroup\$ – gcampbell Jul 17 '16 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.