×

How to add JavaScript to HTML

JavaScript is one of the most important languages today. It is a high-level, interpreted, lightweight programming language that makes web pages more interactive. It is a language of the web. JavaScript makes the web page alive by adding motion to it.

JavaScript is an object-based scripting language. JavaScript supports polymorphism, encapsulation, and inheritance. It does not require any compiler and runs in a web browser. Some of the most popular websites, like Facebook, Google, Amazon, Netflix, and Flipkart, use JavaScript to build their website. It is also used to make small-scale games.

It is known for creating beautiful web pages and applications. We can add JavaScript directly to HTML pages. With the help of HTML, JavaScript is executed. We cannot run JavaScript programs without the use of HTML.

There are three ways in which we can add JavaScript to HTML:

  1. Embedding JavaScript Code
  2. Inline Code
  3. External Code

Let us look at them one by one and understand:

1. Embedding JavaScript Code:

We use a dedicated HTML tag, <script> JavaScript Code </script> tag, to embed JavaScript code in HTML. We can place <script> tag inside the <head> section or in the <body> section of the HTML document.

To keep JavaScript code out of the main content, we place JavaScript code inside the <head> section.

Embedding code is the easiest way to add JavaScript to HTML.

Let us understand it with the help of examples.                     

Example 1:

We will place the JavaScript code inside the <head> section in this example. See the code below:

<!DOCTYPE html>
<html>
<head>
<title> JavaScript in Head </title>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "JavaScript is my favourite programming language";
}
</script>
</head>
<body>


<h2> Adding JavaScript in Head </h2>


<p id="language"> Your favourite programming language. </p>


<button type="button" onclick="myFunction()"> Try it </button>


</body>
</html>

Output:

The output shows the heading, paragraph, and button.

How to Add JavaScript to HTML

When you click the button, JavaScript is executed, and the text is changed.

How to Add JavaScript to HTML

Example 2:

This example will put the JavaScript code inside the <body> section.

<!DOCTYPE html>
<html lang="en-US">
 
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> JavaScript in Body </title>
</head>
<body>
  <script>
      let da = new Date();
      document.body.innerHTML = "<h2> Today's date is " + da + "</h2>"
  </script>
</body>
</html>

Output:

Today’s date can be seen in the output below:

How to Add JavaScript to HTML

2. External Code:

When we have to write large JavaScript code in an HTML document, the code becomes difficult to read. To increase the readability of the code, we can keep large JavaScript code in a separate file and organize it.

The extension of JavaScript file is (.js). We can call the JavaScript file in the HTML document using the source, src attribute inside the <script> tag.

You can also use the same JavaScript file in another HTML document.

We will use the following code to link the external file to the HTML document:

<script scr="filename.js"> </script>

Example 1:

External JavaScript code:

document.write(" You are learning how to add an external JavaScript file to an HTML document. ")
alert(" This file is working. ")

You can call link up this external JavaScript code in an HTML document using the <script> tag as shown in the code below:

<!DOCTYPE html>
<html lang="en-US">
 
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> Adding External JavaScript Code to HTML </title>
</head>
<body>
<h2> External JavaScript Code </h2>
<script src="external.js"> </script>
</body>
</html>

Output:

How to Add JavaScript to HTML

Example 2:

External JavaScript code:

function sayHello() {
    alert("External JavaScript code is executed.");
}
document.getElementById("btn").onclick = sayHello;

You have to link the external JavaScript code to the HTML document, like this,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> External JavaScript File </title>        
</head>
<body>
    <h2> External JavaScript Code </h2>    
    <button type="button" id="btn"> Click here </button>
    <script src="external2.js"></script>
</body>
</html>

Output:

You can see the heading and a button in the output.

How to Add JavaScript to HTML

When you click on this button, external JavaScript is executed, and the message will appear on the screen as shown below:

How to Add JavaScript to HTML

Benefits of using an external JavaScript code in an HTML document:

  • It separates HTML documents and JavaScript code.
  • We can easily manage JavaScript files and HTML documents.
  • The external JavaScript file is initially downloaded only once and stored in the browser’s cache. That’s why web page loading time is reduced.
  • We can reuse the code.
  • We can use the exact code in different HTML documents.
  • It is a good practice to keep HTML, CSS, and JavaScript code in separate files.

Inline Code:

We can add JavaScript code directly to HTML by inlining the code. We can insert code inline using tag attributes like onload, onclick, etc.

Whenever you have to write small code, you can write inline code, but if the code is big, then do not keep the code inline as it reduces the readability of the code and makes it difficult to maintain.

Example 1:

We are using the onclick attribute to add inline code, like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Inline JavaScript Code </title>        
</head>
<body>    
    <h2> Inline Code </h2>
    <button onclick="alert('This code is working!')"> Click here </button>
</body>
</html>

Output:

When you click the button, an alert message will appear on the screen.

How to Add JavaScript to HTML

Example 2:

<!DOCTYPE html>
<html>
    <Title> Example of Inline Code </Title>
<body onload="myFunc()">


<h1> Example of Inline Code </h1>


<script>
function myFunc() {
  alert("Page is loaded");
}
</script>


</body>
</html>

Output:

When you load the page, an alert message will appear on the screen.

How to Add JavaScript to HTML

Browser Support:

It supports the following browsers:

  • Google Chrome
  • Internet Explorer
  • Mozilla Firefox
  • Opera
  • Safari

Related Topics

Html &lt;center> Tag

The term HTML refers to Hyper Text Markup Language. The most widely used markup language for making web pages is HTML. A structure of web page is described in HTML....

3 minutes read.

HTML Anchor

HTML Anchor The HTML anchor tags define a hyperlink that links to other pages on one page. It can create hyperlinks to any web page and files, locations or any other...

3 minutes read.

HTML Forms

Forms are required when we want to collect data from the user. Html forms consists of different fields to take user inputs such as: input, text area, checkbox, password, radio...

4 minutes read.

HTML <strong> tag

The strong element in HTML is used to display the real significant information in bold so that the user or reader will understand it easily. Syntax: <p> <strong>………… </strong> </p> Example Here, we will demonstrate how to...

2 minutes read.

Html <colgroup> Tag

A HTML table's column group is specified by the "colgroup" tag. If you want to apply various properties to one or more <col> elements in an HTML table, then you...

4 minutes read.

HTML Lists

HTML List HTML lists are used to specify data sets. All lists can include one or more elements from the list. HTML lists are available in three different types: Ordered List or...

4 minutes read.

Most Commonly used Tags in HTML

In this tutorial, we'll look at the most popular HTML tags. We know HTML is a fundamental requirement for creating a website. As a result, it is essential to remember...

9 minutes read.

HTML <span> tag

The span tag in HTML is used as an inline container element to mark up a specific or special chunk of a text or a section of a page. If you...

2 minutes read.

HTML5 Tags

HTML5 Tags A list of newly included tags is provided in HTML5. These HTML 5 tags (elements) provide a better structure for the document. This list shows description of all HTML...

3 minutes read.

HTML Code

Before jumping into the topic, let’s understand a common scenario where we have a code snippet in our HTML file. By code snippet, we mean computer code, which is written...

5 minutes read.

Font tag in HTML

HTML stands for Hypertext Mark-up Language and is used to create web pages and other information that can be later displayed in a web browser. It also consists of a...

4 minutes read.

Difference between HTML and DHTML

Introduction to HTML HTML stands for Hypertext Markup Language. It is a standard web language used to create web pages and applications. HTML is used to define the structure and content...

4 minutes read.

HTML &lt;blink> Tag

In HTML, the blink tag is used to create the text which flashes. The blink tag is an inline element in HTML. It is observed that the blink tag used...

2 minutes read.

HTML <section> tag

The section element in HTML is used to define sections in a document. Syntax of Section Tag: <body> <h1>……….</h1> <section> <h2>……….</h2> <p> …………………………</p> </section> <section> <h2>………..</h2> <p>…………………………. <p> </section> </body> Examples of Section Tag Example 1: In this example, we use the HTML "section" element...

3 minutes read.

Responsive HTML5 and CSS3 Tutorial

Introduction to HTML5 Tutorial HTML5 is the latest and upgraded version of HTML. HTML is a hypertext markup language. Technically, it is not a programming language. It is a markup language. HTML...

17 minutes read.

HTML Search Box

The HTML search box is also known as the search bar. It is an input text field that is used to search the content. If the users want to explore...

7 minutes read.

Html &lt;dd> Tag

In an HTML description list, an item's definition or description is indicated using the definition description ("dd" tag). A <dd> tag can contain paragraphs, line breaks, images, links, and lists. It...

4 minutes read.

HTML <sub> tag

The sub element in HTML is used to describe one or more subscript texts. If The sub tag shows the text which is presented in a smaller font and below...

2 minutes read.

HTML Ordered List

We use <ol> tag to make an ordered list in html. An ordered list is made to make a list of items in ordered form, ordered list can be either...

3 minutes read.

HTML <address> Tag

Hyper Text Markup Language, HTML is the best markup language for creating Web pages. HTML consists of a wide variety of elements. In all of these elements, one element is...

4 minutes read.