Reputation: 33
I'm quite sure this question has been asked before, but I couldn't find anything related to my case.
Here's my function
function change(prop) {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
spacing.onchange = change;
blur.onchange = change;
I'm struggling with passing argument to change
function, because if I do spacing.onchange = change("prop")
the function will be executed immediately. I want to avoid using addEventListener
. So here's the question, how can I pass an argument to my function?
Upvotes: 1
Views: 77
Reputation: 1736
Try this:
function onChanges (variables,props) {
variables.forEach((variable, index) => {
variable.onChange=function(event){
return change(props[index]);
}
});
}
onChanges([spacing,blur],[prop1,prop2]);
Upvotes: 0
Reputation: 2829
You can solve that by using high order function feature
function change(prop) {
return function() {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
}
// for example
spacing.onchange = change(/*Your prop*/);
blur.onchange = change(/*Your prop*/);
Upvotes: 2
Reputation: 796
Try setting the variable equal to the function definition.
spacing.onchange = function change(prop) {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
spacing.onchange(arg);
Upvotes: 0