I would like to add a class to an element after being X pixels away from the top of the page and remove that class if you get closer to the top. For that I created the following code
document.getElementsByTagName("body")[0].onscroll = function() {
function offset(el) {
var rect = el.getBoundingClientRect(),
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}
var filter = document.querySelector('.filter-component.navbar');
var divOffset = offset(filter);
console.log(divOffset.left, divOffset.top);
var hereitsfixed = divOffset.top + 55;
if (this.scrollTop >= hereitsfixed) {
filter.classList.add("lol");
} else {
filter.classList.remove("lol");
}
};
So first I am trying to find out how far the element is away from the top (cause that could change) and add 55 pixels to that. I get the correct number here. And then when you scroll down and are that number away from the top or more, it should add the class or remove it. But nothing happens here. Not even an error message. I only get the console.log number (which is alright, I remove it later).
What am I doing wrong here? Can't figure it out.