1

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?

4
  • Don't you mean passing argument to, not from? Commented Jul 29, 2020 at 23:36
  • You need to have a higher order function in your code so that solves your problem Commented Jul 29, 2020 at 23:38
  • @GirkovArpa thank you. Yeah mistyped that bit Commented Jul 29, 2020 at 23:42
  • @SaymoinSam where exactly? Commented Jul 29, 2020 at 23:43

4 Answers 4

2

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*/);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you that really helped. I think it is the most convinient way of doing that
Yes it's the common way JavaScript developers do in this case
1
spacing.onchange = change.bind(spacing, 'prop');

Comments

0

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);

1 Comment

Thank you, but imagine having 100 object like spacing. Adding function manually to every one of them is tough
0

Try this:

function onChanges (variables,props) {
variables.forEach((variable, index) => {
variable.onChange=function(event){
    return change(props[index]);
}
});
}

onChanges([spacing,blur],[prop1,prop2]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.