Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda