'How can I pass function as an argument in javascript?
I would like to create a sticky element that disappears when a certain div
(bottles) get to bottom of the screen.
I have this code that works:
function update() {
const bottles = document.getElementById("bottles");
const rect = bottles.getBoundingClientRect();
const distance = window.innerHeight - rect.bottom; //value is 0 when bottom of bottles is at the bottom of screen
if (distance < 0) {
Array.from(document.getElementsByClassName("sticky-element")).forEach((el) => el.classList.remove("hidden"));
} else {
Array.from(document.getElementsByClassName("sticky-element")).forEach((el) => el.classList.add("hidden"));
}
}
document.addEventListener('scroll', update);
update();
However this is not the best code and it's going to be part of AB testing so the distances would have to be different. Therefore I tried to do something like this but it doesn't work:
function update(distance) {
if (distance < 0) {
Array.from(document.getElementsByClassName("sticky-element")).forEach((el) => el.classList.remove("hidden"));
} else {
Array.from(document.getElementsByClassName("sticky-element")).forEach((el) => el.classList.add("hidden"));
}
}
In case of the option A:
function elementDistance() {
const bottles = document.getElementById("bottles");
const rect = bottles.getBoundingClientRect();
const distance = window.innerHeight - rect.bottom; //value is 0 when bottom of bottles is at the bottom of screen
return distance;
}
document.addEventListener('scroll', update);
document.addEventListener('scroll', elementDistance);
update(elementDistance);
In case of the option B:
function elementDistance() {
const distance = some other values
return distance;
}
document.addEventListener('scroll', update);
document.addEventListener('scroll', elementDistance);
update(elementDistance);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|