Waypoints and Inview, tracking multiple elements using wildcard selector

1.4k Views Asked by At

I have multiple sections on a page with id's like ss-section-story ss-section-problem ss-section-solution and I am trying to track when each of those sections enter and exit the viewport. The problem is, with the current code I have it is only tracking the first section with the id ss-section. I want to be able to track each section entering and exiting.

JS

var inview = new Waypoint.Inview({
element: $('section[id^="ss-section"]')[0],
enter: function(direction) {
  console.log(this.element.id + ' enter');
},
entered: function(direction) {
  console.log(this.element.id + ' entered');
},
exit: function(direction) {
  console.log(this.element.id + ' exit');
},
exited: function(direction) {
  console.log(this.element.id + ' exited');
}
})

I know it must be only tracking the first section because on the element option it is restricted to [0] in that array but when I remove that, I will get undefined on those console.log statements.

What I would want to be able to do it something like but this but judging from the docs, it has no syntax like this :

$('section[id^="ss-section"]').Waypoint.Inview({
enter: function(direction) {
  console.log(this.element.id + ' enter');
},
entered: function(direction) {
  console.log(this.element.id + ' entered');
},
exit: function(direction) {
  console.log(this.element.id + ' exit');
},
exited: function(direction) {
  console.log(this.element.id + ' exited');
}
})

Any suggestions on how I can track each individual section using just one instantiation of the Waypoint.Inview

1

There are 1 best solutions below

0
On

First, u can make collection:

var $collection = $('section[id^="ss-section"]');

Then u make iteration through it:

$collection.each(function () {
   new Waypoint.Inview({
      element: this,
      enter: function(direction) {
         console.log(this.element.id + ' enter');
      },
      entered: function(direction) {
         console.log(this.element.id + ' entered');
      },
      exit: function(direction) {
         console.log(this.element.id + ' exit');
      },
      exited: function(direction) {
         console.log(this.element.id + ' exited');
      }
   })
})

That's all. At least it works for me.