Struggling a bit with nested functions. Problem, I want to call a function from my HTML, but all my JavaScript sits inside to wait for the DOM loaded function.
If I take the function I want to call out of the DOM loaded function, I can not access the variables from inside the DOM loaded function.
-
3Can you share your code.Praveen Alluri– Praveen Alluri2018年01月28日 16:28:47 +00:00Commented Jan 28, 2018 at 16:28
-
1Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.caramba– caramba2018年01月28日 16:31:42 +00:00Commented Jan 28, 2018 at 16:31
1 Answer 1
Presumably when you say you "call a function from [your] HTML" you mean:
<div onclick="yourFunction()">...</div>
...or similar.
This is one of the many reasons not to use onxyz-attribute-style event handlers: You can only call your own functions if they're globals.
Instead, hook up the handlers with modern event handling techniques, such as addEventListener. If you do that, you can use any function in-scope of your code doing the hookup, it doesn't need to be a global anymore.
Simple example:
(function() {
// Not global
function fooClick() {
console.log(".foo clicked");
}
// Hook it up
document.querySelector(".foo").addEventListener("click", fooClick);
})();
<div class="foo">Click me</div>