Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda