Bakhodir
Bakhodir

Reputation: 33

Passing argument to the function inside the object in Javascript

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

Answers (4)

Talmacel Marian Silviu
Talmacel Marian Silviu

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

Saadi Toumi Fouad
Saadi Toumi Fouad

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

Mick
Mick

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

GirkovArpa
GirkovArpa

Reputation: 4912

spacing.onchange = change.bind(spacing, 'prop');

Upvotes: 1

Related Questions