4

I am wondering if there is a way to call a Javascript Function that is inside a Module-type script from a normal script.

For example:

HTML:

<body>
   <button onclick="myFunction()">Click Here</button>
</body>

Normal Script:

function myFunction() {
   alert("Calling Module Function!");
   moduleFunction();
}

Module Script:

/// Module stuff that requires this to be a module script

function moduleFunction() {
   alert("This was called from inside a module script");
   // Info only accessible inside module script
}

I have tried the above code on my site, and I only get an Uncaught Reference error that the function name is not defined. Are there more steps I must take in order to use functions throughout the scripts?

Thanks!

2
  • JS modules/libraries all export something you need to import, whether it's individual methods or an object that provides those methods. How have you imported the the module/library? Commented Nov 26, 2021 at 18:33
  • @jmargolisvt No, I have not. Should I import the function? Maybe import { moduleFunction } from ...? I don't know what the from would be because these are all in one HTML file. Commented Nov 26, 2021 at 18:36

1 Answer 1

4

Bob, If I understand your problem, and if I have anticipated what you are trying to accomplish, the solution is an easy one.

If you have code, a function say, in a script you have typed as module, this function is not available within the html file that has included the module script and calls a function within the module.

 <body>
    <button onclick="myFunction()">Click Here</button>
    <script type="module" src="main.js"></script>
</body>

and the function myFunction is declared in main.js. If you try to call myFunction you will get the error you mentioned "Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick ( with line number in html file where the function was invoked )"

The function is out of scope. Simply write at the end of main.js

window.myFunction = myFunction;

the anchor element NOW has scope of the function as it is in window namespace.

This may not be the issue you came across, but it is head-slapper if you miss it.

Alex

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

1 Comment

This solved my problem and which was the same one as OP.

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.