How to Call JavaScript File in HTML [5 steps]

Last updated

Written by yasmin

How to Call JavaScript File in HTML

Do you want to know how to call JavaScript files in an HTML document?

In this post, we are going to look at 5 simple steps to call or link JavaScript files in HTML.

You can easily call any JavaScript file inside an HTML document using the <script> src attribute of the JavaScript script tag.

Here is a quick example:

You can easily add a <script> tag with a src attribute pointing to your JavaScript file. Simply place the name of your JS file inside the src attribute. Here’s an example:

Example

<body>
    <h1>Hello, World!</h1>

    <!-- Include your JavaScript file -->
    <script src="your-script.js"></script>

</body>
</html>

Below, I’ve outlined all five steps in detail, along with code examples.

Step 1: Create a JavaScript File

Since you already have the HTML files, let’s create the JavaScript file. If you already have a JavaScript file, you can skip this step.

To start, we need to create a JavaScript file, which we will then link to our HTML file.

Here is an example:

Step 1 Create a JS file

Step 2: Add <script> tag in HTML file

Once you’ve created both the HTML and JavaScript files, you’ll need to add a <script> tag to your HTML file to include the JavaScript code.

Open your HTML file and add a <script> tag. See the example below.

Here is an example:

  <body>
    <script></script>
  </body>

Step 3: Add src Attribute to Link the File

After adding the `<script>` tag to your HTML document, the next step is to add the `src` attribute.

This attribute is important because it connects your JavaScript file to the HTML, allowing the script to run on your webpage. Make sure to include the `src` attribute in the `<script>` tag.

Here is an example:

<body>
    <script src=""></script>
</body>

Step 4: Add file name in src Attribute

The last and final step is to mention the JavaScrip file name in the src attribute.

Here is an example:

As shown in the example below, the `src` attribute includes the name of my JavaScript file.

<body>
    <script src="function.js"></script>
</body>

After you add the JavaScript file name to the src attribute in your HTML, the JavaScript file is effectively linked and ready to be executed within your webpage.

Step 5: Save the files, check the path, and run a test

After completing all the steps, save the file and test it to ensure your JavaScript code is running properly with HTML.

To verify that the JavaScript file is correctly linked in the HTML, I’ll create a button that prints ‘Hello’ to the console when clicked.

Here is the example and output:

output

These five easy steps will help you include your JavaScript file in an HTML document. I hope this guide makes linking or calling your JavaScript files in an HTML document straightforward.

Related Posts:

Leave a Comment

Exit mobile version