Technology Programming

HTML Code for Calling a Function in a JS File

    Script Link

    • To make use of functions in an external JavaScript file, a Web page must include a link to the file. The following sample HTML markup demonstrates a link to a JavaScript file listed in the HTML head section:

      <script type="text/javascript" src="myfunctions.js"></script>

      This code allows the page to use functions in a file saved as "myfunctions.js" which is stored in the same directory as the page itself. If the script address resides at a different location, this code needs to reflect the location as part of the "src" attribute.

    Function Outline

    • To call a JavaScript function, you need to know the function outline. To check this, you can locate the function in its source JavaScript file and look at its first line. The following sample JavaScript code demonstrates the outline of a function:

      function doSomethingGood()

      To call this function, the JavaScript code within the Web page must use the function name, as in the following code excerpt:


      When this code executes, the content of the function will execute.

    HTML Markup

    • To call a JavaScript function from HTML, programmers need to decide when the function should execute. Often, functions execute on user interaction with an HTML element. This technique uses event listeners, which you can attach to HTML elements using attributes. The following HTML markup code demonstrates how to specify a JavaScript function to execute when the user clicks an element:

      <input type="button" value="Click to do something good" onclick="doSomethingGood();" />

      When the user clicks this button, the browser will locate the function specified, then execute it.


    • Developers need to tailor their function calls to the details of the functions themselves. Some functions take parameters and some return values when they finish executing. The following example JavaScript function takes a parameter and returns a value:

      function multiplyIt(startNum) {

      return startNum*5;


      The following sample JavaScript excerpt demonstrates calling this function and using the return value:

      var resultNum = multiplyIt(3);


      The code passes a number value to the function and receives another number value in return. It stores the returned value in a variable, then uses this within further processing.

Leave a reply