Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
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);
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!