×

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 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 Youtube

<object> element: It embed the object within the HTML documents and embed plug-ins such as Java applets, PDF readers, Flash Players etc in web pages. Example: <object width="100" height="100" data="bookmark.swf"></object> <embed> element: It defines an embedded...

1 minute read.

HTML <body> tag

HTML means Hyper Text Markup Language, which is most preferred for making Web pages. It explains how a Web page is put together. There are many different elements in HTML,...

3 minutes read.

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....

5 minutes read.

HTML Form Input Types

HTML Form Input Types An important element of the HTML form is < input type= "> in HTML. The type attribute of the input element can be of different types, which...

8 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 &lt;body> alink Attribute

HTML <body> alink Attribute What is HTML? The HTML or HyperText Markup Language is used to design web pages. The file extension name for HTML file is ".html". It was released in...

2 minutes read.

HTML5 Button Tag

HTML Button Tag The < button > tag is used on the webpage to construct a clickable button inside the HTML. Within the < button>....</button > tag, we can place content...

2 minutes read.

HTML Headings

The titles and subtitles of our webpages are known as HTML headings. Let’s not talk about webpages but giving heading to almost everything like normal paragraphs, articles or let it...

2 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 <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.

HTML Frames

Frames in Html is used to divide the browser into different sections where each section can load different Html documents. Collection of frame is known as Frameset. Creating frames:We use frameset...

2 minutes read.

HTML Nested Table

HTML nested table refers to a table that is created inside another table. The table is in the form of rows and columns. From left to right are called horizontal rows,...

5 minutes read.

HTML Code Tag

The code tag in HTML is a phrase tag used to insert a piece of computer programming code. In HTML there is a separate tag named as <code> tag. Sometimes,...

3 minutes read.

HTML Links

It consist of anchor element which is used to create a link between a source anchor and destination anchor. The anchor tag can be embedded between text, image, video or...

2 minutes read.

What does HTML stand for?

HTML stands for Hyper Text Markup Language. We use this markup language to design a web page. Web browsers use this language to showcase text, videos, images, audio and other...

6 minutes read.

HTML <u> tag

Underline Element/Tag: The u tag in html is used to specify the important text or phrase by underline. In earlier HTML versions, this element was known as the "Underline" element, and...

5 minutes read.

HTML Charsets

In this tutorial, we are going to discuss about the charsets in the HTML. The letters, numbers, and several other symbols are shown correctly by the web browser. All of this...

2 minutes read.

HTML Elements

An HTML element is nothing but a starting tag and then some content and then the closing tag. So we can say HTML elements is everything from the starting tag...

3 minutes read.

How to Create a Portfolio Gallery using HTML and CSS?

First, before starting this, the user should know some of the basics of HTML and CSS to create a portfolio gallery. To add more functionality to the website, we can also...

7 minutes read.