Search code examples
javascriptoopscopestatic-variables

How can I define a variable inside a function to be called by an event


How can I set a function variable so can I call outside of the context, like this example

function testSet(elmA,elmB) {
    elmA.onclick = function() {
        elmB.value = "ok";
    };
}

testSet(document.getElementById('a'),document.getElementById('b'));

this doesn't work because when the onclick event is called it is called probably from window and elmB is undefined.

How can I get this working without flooding the global-scope like window.elmB = elmB;?

I'm having this issue with events and callbacks.


Solution

  • elmB is not undefined. Your code works fine, because JavaScript has closures, i.e. variables retain their value for nested functions. Perhaps you're not calling it after the elements exist - say, at the bottom of the page, or in onload?