0

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.

Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 3
    Can you share your code. – Praveen Alluri Jan 28 '18 at 16:28
  • 1
    Please 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](https://stackoverflow.com/help/how-to-ask) page for help clarifying this question. – caramba Jan 28 '18 at 16:31

1 Answers1

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 (or attachEvent if you need to support obsolete Microsoft browsers; if you do, my answer here has a cross-browser function you can use). 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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875