HendrikEng
HendrikEng

Reputation: 684

Converting a jQuery function that increments a counter if scrolled past an element to vanilla Js

I am trying to convert a function that increments a counter once the user scrolls past a section element, i got most of it working but somehow the increment goes nuts after i pass the first section element, is my function to determine the offset to top of each element total wrong?

i also figured that the vanilla JS version outputs slightly different pixels compared to the jQuery solution.

jQuery: codePen

// scoll to next section and back to top
var $scrollSection = $('section');
var $scrollTrigger = $('.section_trigger');
var nextSection = 0;

// turn arrow when scrolled to footer
$(window).scroll(function() {

  //console.log('current distance to top ' +  $('body').scrollTop());
  //console.log('element distance to top ' + $($scrollSection[nextSection]).offset().top);

  while ($('body').scrollTop() > $($scrollSection[nextSection]).offset().top) {
      nextSection++;
      console.log('current section' + nextSection);
  }     
});

JS: CodePen

const sectionElements = document.getElementsByTagName('section');
const scrollTrigger = document.querySelector('.section_trigger');
let nextSection = 0;
let scrollObject = {};
const element = sectionElements[nextSection];

// calculate an elements distance to top 
const elemRect = element.getBoundingClientRect(),
      offset   = elemRect.top - document.body.scrollTop;

// function to get the current distance to top
window.onscroll = getScrollPosition;

function getScrollPosition(){
    scrollObject = {
       x: window.pageXOffset,
       y: window.pageYOffset
    }
}


window.addEventListener('scroll', function() {

// console.log('current distance to top ' + scrollObject.y);
// console.log('element distance to top ' + offset);

 if (scrollObject.y > offset) { 
    nextSection += 1;
    console.log('current section' + nextSection);
  }

});

Thanks a lot

Upvotes: 0

Views: 47

Answers (1)

silentw
silentw

Reputation: 4885

I believe this is what you are looking for:

CodePen

const sectionElements = document.getElementsByTagName('section');
const scrollTrigger = document.querySelector('.section_trigger');
let nextSection = 0;
let scrollObject = {};

// function to get the current distance to top
window.onscroll = getScrollPosition;

function getScrollPosition(){
    scrollObject = {
       x: window.pageXOffset,
       y: window.pageYOffset
    }
}


window.addEventListener('scroll', function() {
  let element = sectionElements[nextSection];

  // calculate an elements distance to top 
  let elemRect    = element.getBoundingClientRect();
  let offset = document.body.scrollTop + elemRect.top;

// console.log('current distance to top ' + scrollObject.y);
// console.log('element distance to top ' + offset);

 if (scrollObject.y > offset) {
    nextSection += 1;
    console.log('current section' + nextSection);
  }
});

Upvotes: 1

Related Questions