How to add JavaScript to HTML page

By Adding JavaScript to HTML pages is essential for developing dynamic and interactive web applications. JavaScript may help you add more functionality and improve the user experience whether you’re creating a simple website or a sophisticated online application.

You can use it to validate form, file upload using AJAX, submit a form, etc. You can add JavaScript code using an external .js file or directly specify code between <script > tags on the page.

In this tutorial, I show both ways to include JavaScript code on the page.


Contents

  1. Include External .js file
  2. Embedding JavaScript code
  3. Conclusion

1. Include External .js file

Javascript –

Create script.js file at the project root.

Create btnclick() function that displays an alert message when gets called.

Completed Code

function btnclick(){
   alert('clicked');
}

HTML –

Create a button and added a click event that calls btnclick() function.

To include .js file use <script > tag and specify file path in src attribute. If your js file is stored in js/ folder then your file path will be js/script.js.

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

Completed Code

<!DOCTYPE html>
<html>
<head>
   <title>How to add JavaScript to HTML page</title>
</head>
<body>

   <button onclick="btnclick();">Click</button>

   <!-- Script -->
   <script src="script.js" type="text/javascript"></script>
</body>
</html>

2. Embedding JavaScript code

Specify your Javascript code between <script > tags. You can place it either in <head > or <body> section.

Example –

Created a button and added click event that calls btnclick() function. I specified <script > tag in the <body> section.

Create btnclick() function that alerts a message.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <title>How to add Javascript In HTML</title>
</head>
<body>

   <button onclick="btnclick();">Click</button>

   <!-- Script -->
   <script type="text/javascript">
   function btnclick(){
       alert('clicked');
   }
   </script>
</body>
</html>

3. Conclusion

Your web applications’ usability and user experience can be considerably improved with JavaScript. By following the steps outlined in this article, you can easily link your JavaScript files to your HTML pages.

You can use both ways to include JavaScript code on your page. It is better to create separate .js file if the code is getting long.

If you found this tutorial helpful then don't forget to share.

Leave a Comment