To make these languages work together you have to add your JavaScript file into your HTML document. For the purpose of doing so, you can add your external JavaScript file to your HTML document.
Adding JavaScript File
To add an external JavaScript file in your HTML document, assign the link of your file to the src attribute in the <script> tag.
Syntax
Or,
Or,
Points to remember!
- You can place these <script> tags either in the <head> section or in the <body> section.
- As indicated in the syntax the extension of external JavaScript files should be .js.
- It is beneficial to use external JavaScript files when you have to use the same code in multiple HTML documents. Moreover, this will enhance the readability and maintainability of your document.
Below we have discussed different approaches to add your JavaScript file in HTML.
Condition 1: Adding JS file using the file path
In order to add your external JavaScript file into your HTML document, you have to provide your file path in the src attribute of the <script> tag.
Suppose we have our HTML and javascript files in our directory:
HTML File
In the above example, we are creating an input field that asks the user to input his/her name.
Meanwhile, we have defined our function in the JavaScript file using the following code.
alert("Your name has been submitted!");
}
Once the user presses the submit button, an alert message is displayed.
In another scenario, when your HTML file is placed in a separate folder and the JavaScript file in another folder as shown below.
Use the following syntax, to add your file path to the src attribute in the <script> tag.
Condition 2: Adding JS file using URL
When you want to add a JavaScript file that is stored online then you have to simply add the url of your online JavaScript file in the src attribute of your <script> tag.
Example
In the above example, we added the url of an external JavaScript file that is stored online. The online JavaScript file looks like this.
In the above file we have defined our function that is intended to display an alert message when the user presses the submit button.
Output
Following these steps, you can easily add your external JavaScript file to your HTML document.
Conclusion
To add a JavaScript file in HTML provide your JavaScript file path to the src attribute of the <script> tag or if you are using a JavaScript file that is stored online then you have to add the URL of that file. In this post, we have discussed in detail the approaches to adding your JavaScript file in HTML by demonstrating them through examples.