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

107
Views
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
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!