how to call javascript function from .html in a .js file
Solution 1
Your script tags are incorrectly nested.
<script type="text/javascript">
function fn() {
.....
}
</script>
<script type="text/javascript" src="js/foo.js"></script>
And to actually answer your question: Yes, it is possible.
Solution 2
Definitely possible, but not recommended. If you are calling a function that has been nested within your html, that function should probably be in the file that is calling it. Unless of course, you have your own library of helper and utility functions, and this function you are calling could reside there. This will keep a nice separation between your program logic(JavaScript), and your content(HTML). for example:
<!-- Your Helper Library that holds useful functions -->
<script type="text/javascript" src="helpers.js"></scrip>
<!-- Your Program Logic that makes use of your helper functions -->
<script type="text/javascript" src="programlogic.js"></scrip>
I hope this has helped!
-Mike
swoosh
Updated on June 14, 2022Comments
-
swoosh almost 2 years
Is it possible to call a javascript function from an .html file while in a .js file? For example, I have this in my foo.js:
$(document).ready(function() { fn(); })
And I want to call fn() which is in my index.html:
<script type="text/javascript" src="js/foo.js"></script> <script type="text/javascript"> function fn() { ..... } </script>
When I do this, it doesn't seem to be calling fn().
-
swoosh almost 12 yearsThat solved my problem, but actually the problem was that my javascript include was delcared before the function. Changing the order solved my problem. thx.