×

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 Unordered List

In HTML, we have <ul> tag which defines the unordered list. And it is also known as bulleted list, because as we know it is not ordered list therefore it...

2 minutes read.

Scrolling Text in HTML

The <marquee> tag can be used to produce scrolling text in HTML, or (the recommended way) you can make scrolling text with CSS. You may achieve horizontal scrolling of your...

5 minutes read.

HTML Event Attributes

HTML Event Attributes If a browser responds to the user behavior, an event is called. For example, if we click on the submit button, a box of details will appear on...

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

Figma to HTML

Introduction: Figma is a tool that is used in design, specifically in the creation of user interfaces and experiences and is well favoured by designers due to its integration of teamwork...

5 minutes read.

How to Save HTML File

Introduction Simply saving a document created in FrameMaker as an HTML file is all that is required to convert it to HTML. The process of saving as HTML involves establishing specifications...

5 minutes read.

How to Create a Table in HTML

How do You Define an HTML Table? In HTML, material organized into rows and columns is referred to as a table. Tables may show data such as goods and their costs,...

5 minutes read.

Beautiful Soup Remove HTML Tags

What is Beautiful Soup? A Python module called Beautiful Soup was created for rapid prototyping tasks like screen scraping. Its three attributes give it power: A toolbox for breaking down a text...

7 minutes read.

How to Add Audio Files in HTML

The <audio> tag came with HTML5, and changed everything about how we add sound to our sites. We may use this simple tag to embed and control audio files straight...

10 minutes read.

Full Form of href in HTML

Introduction: In HTML, the href attribute represents "Hypertext Reference." It is used to indicate a hyperlink's destination inside the (anchor) element. The URL (Uniform Resource Locator), or the place to which...

9 minutes read.

HTML Table Fix Column Width

The width property, along with CSS styles, can be used to adjust the column widths in a table. To determine the width of every column, use the width attribute within...

3 minutes read.

HTML Paragraphs

In html, there are some elements which starts with new line and one of them is paragraph. Which is said to be a block of text. In html <p> tag...

4 minutes read.

Date Picker in HTML

What is a Date picker? A date picker in HTML is a user interface element that allows users to select a date from a graphical calendar widget. It is a type...

4 minutes read.

HTML Tag for Tab

Acquiring the ability to insert spaces in HTML can improve your formatting as a site designer. Your HTML content will read easier if it has spaces in it. In contrast to...

4 minutes read.

HTML Popup

What is HTML? Current technology for creating templates and content on the World Wide Web uses the common language called HTML, short for Hypertext Markup Language. They offer structure and content...

5 minutes read.

HTML Pie Chart

Pie charts are a popular form of data visualization form that presents percentages or proportions of a whole. They are often utilized to pinpoint data in a visually appealing and...

11 minutes read.

html &lt;th&gt; tag

What is <th> Tag? The HTML `<th>` tag has an important role in the creation of a table header cell in a web page; it is used to describe the word...

7 minutes read.

HTML Align Tag

What is HTML? Hypertext Markup Language, or HTML, is the common markup language used for web page creation and design. It defines a web page's fundamental organization and content, including headers,...

3 minutes read.

How to Add Favicon in HTML

Introduction to Adding a Favicon in HTML A favicon and a symbol of your site are needed because this name has evolved from the combination of the words and favorite icon....

12 minutes read.

HTML Cleaner

Introduction HTML Cleaner offers a user-friendly interface that simplifies HTML editing and cleaning. It allows you to extract clean content from HTML code, eliminating extraneous spaces and making it more legible....

5 minutes read.