I need to know when a user has scrolled to a certain element with an id.
This is what I've tried:
$(window).on('load', function() {
let elembestellen = document.querySelector('#bestellen');
var bestellen = elembestellen.getBoundingClientRect().top;
let eleminformatie = document.querySelector('#informatie');
var informatie = eleminformatie.getBoundingClientRect().top;
let eleminspiratie = document.querySelector('#inspiratie');
var inspiratie = eleminspiratie.getBoundingClientRect().top;
let elemreviews = document.querySelector('#reviews');
var reviews = elemreviews.getBoundingClientRect().top;
$(window).scroll(function(){
w = Math.floor( $(window).scrollTop());
if(window.outerWidth > 767) {
// console.log(bestellen);
if( (w > parseInt(bestellen)) && (w < parseInt(informatie)) ){
console.log('#bestellen reached');
}
if( (w > parseInt(bestellen)) && (w > parseInt(informatie)) && (w < parseInt(inspiratie)) ){
console.log('#informatie reached');
}
// if( (w > parseInt(bestellen)) && (w > parseInt(informatie)) && (w > parseInt(inspiratie)) && (w < parseInt(reviews)) ){
// console.log('inspiratie');
// }
// if(w > parseInt(informatie)){
// console.log('informatie');
// }
}
});
});
The problem is my console logs #bestellen reached
at the correct time when I load the page all the way scrolled to the top. But if I scroll down a bit, and refresh the page, the logged #bestellen reached
does not appear at the right moment again. It appears way to early.
How can I make sure the logs only fire when the element with the correct id has been reached on the page, no matter what part of the page is loaded?