Introduction to HTML : JavaScript in HTML

JavaScript in HTML

JavaScript (JS) is an interpreted and lightweight programming language used to make web pages (HTML) "come alive" by adding dynamic behaviours and interactivity. 

There are two main ways of adding JavaScript to an HTML document: either inline or via an external JS file.

Adding JavaScript inline:

JavaScript code can be added between <script></scripts> tags within the head or body section or after the body section of an HTML document.

<!DOCTYPE html>
<html>
   <head>
       <title>Teachsomebody</title>
       <script>
           document.body.innerHTML = "<p>I am legend by Will</p>"
       </script>
   </head>
   <body>
   </body>
</html>

This will output 'I am legend' within a paragraph on the HTML page. 

The script tags and code could also be moved into the body tags to produce the same output.

Adding JavaScript via an external file:

To add JavaScript via an external file, create a file with a ".js" extension. Example test.js. Within this file, place your JavaScript code (without the script tags) and add the path to the file as the src attribute value of the script tags defined in the HTML document.

Example of an external Javascript file: test.js

document.body.innerHTML = "<p>I am legend by Will</p>"

HTML document referencing the external test.js script (assuming test.js is in the same directory as the HTML document)

<!DOCTYPE html>
<html>
   <head>
       <title>Teachsomebody</title>
       <script src="test.js" type="text/javascript" >
       </script>
   </head>
   <body>
   </body>
</html>

This will produce the same effect as the inline code in the earlier example. 

Having JavaScript code in external files allows code to be more modular and easier to separate concerns in big web development projects.


course logo
Introduction to HTML
Number of sections:
11
Content length:
Delivery formats: