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

111
Vistas
Add callback with parameters to dynamically added elements in Javascript

I need to create a lot of sliders in HTML/Javascript and created a function for this:

function createSliderAt (place, name, min, max, step, value){
    let slider = document.createElement("input");
    slider.setAttribute ("type", "range");
    slider.setAttribute ("id", name);
    slider.setAttribute ("min", min);
    slider.setAttribute ("max", max);
    slider.setAttribute ("step", step);
    slider.setAttribute ("value", value);
    
    slider.addEventListener('input', function(e) {
        console.log (this.id, this.value);
    });

    let p = document.getElementById (place);
    p.append(slider);

    return slider;
}

Then I can add sliders:

let slider1 = createSliderAt ("sliders", "slider1", 0, 100, 0.1, 0);
let slider2 = createSliderAt ("sliders", "slider2", 100, 1000, 1, 200);
let slider3 = createSliderAt ("sliders", "slider3", 0, 10, 0.1, 3);

Now I would also like to add callbacks to the function argument list. Callbacks being called when slider is changed, passing on the new value.

I tried changing the function head adding callback...

function createSliderAt (place, name, min=0, max=100, step=0.1, value=0, callback){

...and then in the function body add:

    slider.addEventListener('input', callback(this.value));

The idea was to add functions and then pass as arguments when creating a slider. In this style:

function foo (p){
    console.log("foo: " + p)
}

let slider1 = createSliderAt ("sliders", "slider1", 0, 100, 0.1, 0, foo);

But I get: Uncaught TypeError: callback is not a function. I understand that in the definition of function createSliderAtthe type of the arguments are unknown to the code in the function. But I believe it should be possible to pass functions as arguments, but I don't understand how.

I read this and similar articles (often with setTimeOut) but don't see how this applys to my case.

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