I have multiple javascript functions in my html page. One of them, by far the biggest, is executed on a button click. If I moved that function into a separate .js file, what would be the syntax to have the onclick run that file?
I have multiple javascript functions in my html page. One of them, by far the biggest, is executed on a button click. If I moved that function into a separate .js file, what would be the syntax to have the onclick run that file?
Share Improve this question asked Apr 11, 2012 at 1:17 WilsonWilson 8,76820 gold badges72 silver badges102 bronze badges 1-
Just make sure the script file is loaded before you try to use the functions defined within it. With jquery, for example, you'd wrap your calling code within a
$(function () { /* here */ });
. – Chris Farmer Commented Apr 11, 2012 at 1:22
4 Answers
Reset to default 6If the name of the function is still the same, then you don't have to do anything except include the script in your html somewhere before any code uses it, like so:
<script src="/yourscript.js" type="text/javascript"></script>
Your javascript functions can be in any number of files. You just need to add the reference to the .js file like this inside the tag:
<script type="text/javascript" src="path/to/scripts/filename.js"></script>
You don't have to change anything.
Just include your javascript file in your HEAD
section, and the rest may remain the same. :-)
Your onclick
doesn't run the file. It runs the function contained within that file. You wouldn't need to change the onclick
syntax to make that happen.