Fuiba Fuiba -4 years ago 111
jQuery Question

How to attach the Vivus listener to the scroll of a div?

I have a div that has

overflow: scroll
on it, and the svgs inside should animate on scroll, however they only animate in body (document), if I scroll down inside the div, it doesnt fire.

I tried to fire Vivus on scroll, but every time I scroll down or top it animates.

$('#div-scrollable').scroll(function () {
new Vivus(document.querySelector('#svg'),{duration: 50});
});


I want to animate the svg the first time I scroll down inside the div.

jsFiddle - default

jsFiddle - scroll function

Answer Source

Setting a flag is enough to handle the animation occurrence.

First, change your css to overflow-y: scroll; like below

#div-scrollable {
  width: 500px;
  max-height: 300px;
  overflow-y: scroll;
  border: 1px solid gray;
}

Then, use following script

flag = true;
$('#div-scrollable').scroll(function () {
    var DistanceFromBottom = Math.floor($("#div-scrollable")[0].scrollTop - ($("#div-scrollable")[0].scrollHeight - $("#div-scrollable").height()));
    if(-1 <= DistanceFromBottom && DistanceFromBottom <= 1 && flag){
        flag = false;
   }
   if(flag) new Vivus(document.querySelector('svg'),{duration: 50});

});

I worked and tested it on your jsfiddle and it should work. let me know if there is any issue yet.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download