0

How to pass local variable value from function to addEventListener function?

Here is code for example(JavaScript),

function f(){

   var x = new Audio('Audio URL')
   var divID = document.getElementById('id of a div');

   if(divID){
      divID.addEventListener("webkitAnimationEnd",g);
      divID.addEventListener("animationend",g);
  }
}


function g(){
    //Code that uses variable x value and functions i.e x.pause() or x.play()
}

How to pass the variable x value in function f() to function g() in addEventListener?

5
  • 1
    the function g is callback function so you can pass data to g from webkitAnimationEnd Commented Nov 22, 2017 at 21:55
  • Can I pass var x value to g() from webkitAnimationEnd? if then how? Commented Nov 22, 2017 at 21:56
  • you can use .bind to return a new bound function with seeded arguments. not a great solution, but a possibility. g.bind(elm, x) Commented Nov 22, 2017 at 21:57
  • The first argument to addEventListener should be a quoted string. Commented Nov 22, 2017 at 22:04
  • @Barmar thx! edited it. Commented Nov 22, 2017 at 22:14

2 Answers 2

2

You can try something like:

function f(){

   var x = new Audio('Audio URL')
   var divID = document.getElementById('id of a div');

   if(divID){
      divID.addEventListener(webkitAnimationEnd, () => g(x));
      divID.addEventListener(animationend, () => g(x));
  }
}


function g(x){
    //Code that uses variable x value and functions i.e x.pause() or x.play()
}

Or, if you want ES5 support, divID.addEventListener(webkitAnimationEnd, function() { g(x); });

Sign up to request clarification or add additional context in comments.

Comments

1

Probably you'll want to do this with a closure:

function f(){

   var x = new Audio('Audio URL')
   var divID = document.getElementById('id of a div');

   if(divID){
      divID.addEventListener(webkitAnimationEnd, makeG(x));
      divID.addEventListener(animationend, makeG(x));
  }
}

function makeG(x) {
    return function() {
        //Code that uses variable x value and functions i.e x.pause() or x.play()
    }
}

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.