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.

2
  • 3
    Can you share your code. Commented Jan 28, 2018 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 page for help clarifying this question. Commented Jan 28, 2018 at 16:31

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.