-2

I have this simple onclick eventfunction and i would like to know if it's possible to acces the variable that is inside it and use it outside this function, if not is there a way to do something similar?

document.querySelector('.check-parent').addEventListener('click', function() {
    var a = 'abc';
    return a;
});
        
console.log(a);

P.S.

In my homepage code i have 3 forms, each form has one id and it needs to display errors in case the fields are not completed properly. And when i click submit i get the parent id and that id goes in a switch function and determins with form it was and what errors needs to display

dan
  • 3
  • 2
  • 2
    That wouldn't work anyway, because the event listener is asynchronous. What *exactly* are you trying to accomplish? – Blazemonger Nov 06 '17 at 17:09
  • 2
    you can declare variable outside this function and access anywhere you want – Muhammad Usman Nov 06 '17 at 17:09
  • Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – zfrisch Nov 06 '17 at 17:13
  • i tryed to define it outside and then acces it inside but i need the result of the click event. I have on my homepage 3 contact forms and to display messages under each field in case of an error i need to know what id the parent has, when i know that i will display the correct errors – dan Nov 06 '17 at 17:15
  • If you want to access data *inside* the click handler, put the code *inside*. – Jonas Wilms Nov 06 '17 at 17:23

1 Answers1

0

You'll have to get a few things correct:

  1. The this variable changes inside the callback since the scope changes. Hence bind outer this to your clickhandler(bind(this) in below snippet)

  2. console.log(a) would not print undefined since it's again in different scope. You'll have to trigger this call only after a click event is performed. Hence wrap it in a function & call this from the handler by passing the value.(this.fromClick(innerVariable) in below snippet)

Below's a sample snippet(ES5 demo & ES6 demo):

this.count =0;

document.getElementById('myButton').addEventListener('click', function() {
//Access outer variables
this.count++;
document.getElementById('buttonCount').innerHTML = this.count;

//Send something outside 
var innerVariable = 'String from  click handler!!';
this.fromClick(innerVariable);

}.bind(this));

this.fromClick = function (innerVariable) {
 alert(innerVariable);
}
knomdlo
  • 398
  • 2
  • 14