2

I am struggling to get a last bit of my code to work. Problem is I need to fire a function when a user scrolls past a div

So the structure of my html looks roughly like this

<div class="panel-grid-cell">
  <div id="pgc-1">...</div>
  <div id="pgc-2">...</div>
  ...
  <div id="pgc-n">...</div>
</div>

So the idea is when users passes a div with id="pgc-1" fire a function and so on for the rest of them.

Each of these divs has a li a item with the href attached, so I my function would look something like this

ga('send','event','scroll',city,$(this).text())

where this would be corresponding li a with the href

At the moments what I have is this. A function to loop through div's and store their id's in array. And a build a li a menu.

 var li="";
 var linames = ["Intro","1925","1935","1945","1955","1965","1975","1985","1995","2005","Now"];
 var i = 0;
 function getSectionIDs()
 {
    $("div.panel-grid-cell").children().each(function() {
    if(linames[i] !== undefined)
    {
        li += "<li><a href='#"+$(this).attr('id')+"'>"+linames[i]+"</a></li>";           
    }
    i++;
    });
 $("ul.timeline-items").append(li);
 }

Now I also have a function that checks how far did I scroll and change a class for each li item.

function onScroll(event){
  var scrollPos = $(document).scrollTop();
  $('ul.timeline-items li a').each(function () {
      var currLink = $(this);
      var refElement = $(currLink.attr("href"));
      if (refElement.position().top -75 <= scrollPos && refElement.position().top+75 + refElement.height()-75 > scrollPos) {
         $('ul.timeline-items li a').removeClass("active");
         currLink.addClass("active");
      }
      else{
         currLink.removeClass("active");
      }
    });
    }
    $(document).on("scroll", onScroll);

This Code does not what I want, because it constantly check If I have passed the div or not, but I need to fire my function only once.

Any help?

Andrejs Gubars
  • 584
  • 7
  • 30
  • It may help you [Detecting when user scrolls to bottom of div with jQuery](http://stackoverflow.com/questions/6271237/detecting-when-user-scrolls-to-bottom-of-div-with-jquery). – hmd Apr 26 '16 at 06:12
  • 1
    Use `one` method of jQuery if you want to fire a method only once... refer http://api.jquery.com/one/ – RRR Apr 26 '16 at 06:48
  • hmm, good point about `one`, need to find a smart way to attach it. – Andrejs Gubars Apr 26 '16 at 08:03

1 Answers1

0

Found a solution myself the other day,

Inside a scrolling function just put a condition when $(document).scrollTop() equals to refElement.offset(), fire a function, and it works perfectly.

Meaning that check how far user has scrolled and if this value is equals to the offset of the div, fire a function.

Andrejs Gubars
  • 584
  • 7
  • 30