Nida Nida - 5 months ago 17
jQuery Question

Animation on browser scrolling

I have used jQuery like below lines of code

$(window).load(function() {
$(".shuffle").each(function() {
$(this).circulate({
speed: Math.floor(Math.random()*300) + 100,
height: Math.floor(Math.random()*100) - 70,
width: Math.floor(Math.random()*100) - 70
});
});
});


The circular animation works fine on the page loading.

The html is like

<div id="target">
<div class="shuffle"></div>
<div class="shuffle"></div>
<div class="shuffle"></div>
<div class="shuffle"></div>
</div>


Now I want that when user is scrolling down the browser, as he reaches the div with id target section, the animation should get started...

Please help !!!

Answer
var isElementInViewport = function ($element) {
    //element has to be a jQuery element with length > 0
    var domElement = $element[0];
    var height = $element.outerHeight();
    var rect = domElement.getBoundingClientRect();
    return (
        rect.top >= 0 - height &&
        rect.bottom <= $(window).height() + height
    );
};

var shuffle = function($element) {
 //only shuffle elements within the target
 $(".shuffle", $element).each(function() {
    $(this).circulate({
      speed: Math.floor(Math.random()*300) + 100,
      height: Math.floor(Math.random()*100) - 70,
      width: Math.floor(Math.random()*100) - 70
     });
  });
}

var flag = false;
var $target = $('#target');
$(document).on('scroll', function(){
  if(isElementInViewport($target)){
    if (!flag) {
      flag = true;
      shuffle($target);
    }
  }
});
Comments