'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 createSliderAt
the 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|