How to add JavaScript to HTML page

With Javascript, you can functionality on your webpage. You can use to validation 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. External .js file
  2. Embedding
  3. Conclusion

1. External .js file

Javascript –

Create script.js file.

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.

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

Completed Code

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

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

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

2. Embedding

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

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