How To Add JavaScript to HTML
Introduction
JavaScript, also abbreviated to JS, is a programming language used in web development. As one of the core technologies of the web alongside HTML and CSS, JavaScript is used to make webpages interactive and to build web apps. Modern web browsers, which adhere to common display standards, support JavaScript through built-in engines without the need for additional plugins.
When working with files for the web, JavaScript needs to be loaded and run alongside HTML markup. This can be done either inline within an HTML document or in a separate file that the browser will download alongside the HTML document.
This tutorial will go over how to incorporate JavaScript into your web files, both inline into an HTML document and as a separate file.
Add JavaScript to HTML
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script>
that wraps around JavaScript code.
The <script>
tag can be placed in the <head>
section of your HTML or in the <body>
section, depending on when you want the JavaScript to load.
Generally, JavaScript code can go inside the document <head>
section to keep it contained and out of the main content of your HTML document.
However, if your script needs to run at a certain point within a page’s layout when using document.write()
to generate content, you should put it at the point where it should be called, usually within the <body>
section.
Example of Inline JavaScript
Let’s consider the following blank HTML document with a browser title of “Today’s Date”:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Today's Date</title>
</head>
<body>
</body>
</html>
Now, we will add the following JavaScript code to the document:
let d = new Date();
alert("Today's date is " + d);
Add the code to the <head>
section:
<script>
let d = new Date();
alert("Today's date is " + d);
</script>
Working with a Separate JavaScript File
For larger scripts or scripts used across several pages, JavaScript code is generally placed in separate files. Here’s how you can use an external JavaScript file:
Create a new JavaScript file, script.js
, and include the following code:
let d = new Date();
document.body.innerHTML = "<h1>Today's date is " + d + "</h1>";
Reference this file in your HTML document:
<script src="js/script.js"></script>
Complete HTML Example
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Today's Date</title>
</head>
<body>
<script src="js/script.js"></script>
</body>
</html>
Conclusion to Add JavaScript to HTML
This tutorial covered how to add JavaScript to HTML, both inline and as a separate file. Using these methods, you can effectively integrate JavaScript into your web projects.