title: How do I run a custom function ONLY the first time a user scrolls to a certain element?
body: <p><strong>The problem:</strong> </p>
  
  <p>I have a fancy looping image carousel that needs to start—from a specific first slide—when the user scrolls to a certain div. It should NEVER restart if the user scrolls up/down and back to that div. </p>
  
  <p>I can only currently get it to start when the user scrolls to the div—and then it gets screwed up when you scroll away and back to it, which I assume is because the function starts running again.</p>
  
  <p><strong>What I'm trying to achieve:</strong></p>
  
  <ol>
  <li>User scrolls to certain div</li>
  <li>Fancy image carousel animation function runs</li>
  <li>If user scrolls up/down and back to the div, the animation function never starts again.</li>
  </ol>
  
  <p><strong>My (anonymized, sorry guys!) code:</strong></p>
  
  <p><a href="http://jsfiddle.net/annablabber/h8pqW/" rel="nofollow">http://jsfiddle.net/annablabber/h8pqW/</a></p>
  
  <p>HTML</p>
  
  <pre><code>&lt;p class="scroll_down"&gt;Scroll down...&lt;/p&gt;
  
  &lt;div class="animation_container"&gt;You should get an alert only once here—the first time you scroll to this div.&lt;/div&gt;
  </code></pre>
  
  <p>CSS</p>
  
  <pre><code>.scroll_down {
    margin-bottom: 1000px;
  }
  
  .animation_container {
    width: 300px;
    height: 200px;
    background-color: red;
    padding: 30px;
    color: white;
    margin-bottom: 1000px;
  }
  </code></pre>
  
  <p>jQuery</p>
  
  <pre><code>// 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 &lt;= docViewBottom) &amp;&amp; (elemTop &gt;= 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 );
      }
    };
  } 
  </code></pre>
  
  <p>Apologies for the script clearly written by a visual designer. Let me know if the question isn't clear enough from the anonymized code.</p>