JSFiddle - React, Tailwind, and code Playground

by annablabber

HTML

<p class="scroll_down">Scroll down...</p>

<div class="animation_container">You should get an alert only once here--the first time you scroll to this div.</div>

CSS

.scroll_down {
    margin-bottom: 1000px;
}

.animation_container {
    width: 300px;
    height: 200px;
    background-color: red;
    padding: 30px;
    color: white;
    margin-bottom: 1000px;
}

JavaScript

// The fancy function for my animations
function doSomeComplicatedStuff() {
    alert("...and here's where the complicated animations happen!");
}

// The function to check if div.animation_container is scrolled into view
function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}

// If div.animation_container is scrolled into view, run the fancy function
$(window).on('scroll', function() {
  if (isScrolledIntoView('.animation_container')) {
    run_once(function() {
      doSomeComplicatedStuff();
    });
  }
});

// The function that's supposed to make sure my fancy function will only run ONCE, EVER
function run_once( callback ) {
    var done = false;
    return function() {
        if ( !done ) {
            done = true;
            return callback.apply( this, arguments );
        }
    };
}