0

I'm trying to pass a variable from an addEventListener function to another. How could you pass a variable if both of the functions don't have a name? Thank you!

     document.getElementById('rect').addEventListener('keyup', function() {
       var index = 5;

     }
      document.getElementById('rte').addEventListener('click', function() {



     }
3g33
  • 1
  • You would not pass it at all. You would define the variable that is in a scope both functions have access to (e.g. global scope). Every JavaScript function is a closure. – Felix Kling Dec 03 '18 at 21:32
  • I can't use global variable, that's the problem. The function I wrote it's just a simple example to explain what I'm trying to achieve @goldie – 3g33 Dec 03 '18 at 21:35
  • why though? ... ? – Jonas Wilms Dec 03 '18 at 21:35
  • @FelixKling so I can't pass it? – 3g33 Dec 03 '18 at 21:36
  • @JonasWilms if I can pass the variable inside the first function outiside the function, well, that work too – 3g33 Dec 03 '18 at 21:39
  • Passing something to a function implies that you are calling the function. But you are not calling the event handlers, the browser is calling them when the event occurs. – Felix Kling Dec 03 '18 at 21:39
  • Maybe you want [Define global variable in a JavaScript function](https://stackoverflow.com/q/5786851/218196) – Felix Kling Dec 03 '18 at 21:40
  • @FelixKling Got it, thank you! – 3g33 Dec 03 '18 at 21:43
  • No, Mr. Bill, No! No global variables. Wrapping the variable in a global function is the same thing. [jQuery has an event.data property](https://api.jquery.com/event.data/). The example hints that you could, w/o jQuery, bind data to some kind of "eventArgs" object that is (perhaps) created on the Event.prototype. – radarbob Dec 03 '18 at 22:25

0 Answers0