Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Javascript Function In a Module Type Script From A Normal Script

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!

like image 459
rxnen Avatar asked Nov 08 '25 01:11

rxnen


1 Answers

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

like image 175
Alex Ainsworth Avatar answered Nov 09 '25 16:11

Alex Ainsworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!