The issue at hand:
I am working with a sophisticated looping image carousel that needs to initiate - starting from a specified initial slide - as soon as the user scrolls to a specific division. It must not restart if the user scrolls up or down and then returns to that same division.
Currently, I am only able to get it to start when the user scrolls to the division, but it malfunctions when scrolling away and back, likely due to the function retriggering.
My goal is to achieve the following:
- User scrolls to a particular division
- The fancy image carousel animation function executes
- If the user scrolls back to the division, the animation function should not restart
The code in question (anonymized for privacy reasons):
http://jsfiddle.net/annablabber/h8pqW/
HTML
<p class="scroll_down">Scroll down...</p>
<div class="animation_container">An alert should display only once here - upon first scroll to this division.</div>
CSS
.scroll_down {
margin-bottom: 1000px;
}
.animation_container {
width: 300px;
height: 200px;
background-color: red;
padding: 30px;
color: white;
margin-bottom: 1000px;
}
jQuery
// The complex animations function
function doSomeComplicatedStuff() {
alert("...and here's where the complicated animations happen!");
}
// Function to check if div.animation_container is within view after scrolling
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, execute the animations
$(window).on('scroll', function() {
if (isScrolledIntoView('.animation_container')) {
run_once(function() {
doSomeComplicatedStuff();
});
}
});
// Ensuring that my animations execute only once
function run_once(callback) {
var done = false;
return function() {
if (!done) {
done = true;
return callback.apply(this, arguments);
}
};
}
Please excuse the slightly amateurish script. Do let me know if further clarification is needed based on the anonymized code provided.