I am currently developing a progress bar animation that is designed to animate from 0 to a specified percentage when the progress bar becomes visible within the browser's viewport. The animation must always trigger when the element is scrolled into view, and scrolling it out of view should reset the animation.
Below is the code snippet that I have been working on:
var $animation_elements = $('.progressAnimation');
var $window = $(window);
function check_if_in_view() {
var window_height = $window.height();
var window_top_position = $window.scrollTop();
var window_bottom_position = (window_top_position + window_height);
$.each($animation_elements, function() {
var $element = $(this);
var element_height = $element.outerHeight();
var element_top_position = $element.offset().top;
var element_bottom_position = (element_top_position + element_height);
//check to see if this current container is within viewport
if ((element_bottom_position >= window_top_position) &&
(element_top_position <= window_bottom_position)) {
$element.animate({
"width": (600 * $($element).data("percent")) / 100
}, 3000);
} else {
$element.animate({
"width": "0"
}, 1000)
}
});
}
$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
body{
height:4000px;
margin-top:800px;
}
.myContainer{
width:1000px;
margin:50px auto;
}
.myContainer .progressBackground{
width:600px;
height:40px;
margin:0 auto 40px;
background-color:#eaeaea;
}
.myContainer .progressAnimation{
width:0;
height:100%;
background-color:#00f36d;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myContainer">
<div class="progressBackground">
<div class="progressAnimation" data-percent="80">
</div>
</div>
<div class="progressBackground">
<div class="progressAnimation" data-percent="60">
</div>
</div>
</div>
Please remember to run the code snippet in fullscreen mode for optimal viewing experience.