It is not hard to add javascript to HTML. There are “<script> </script>” tag in between you can insert JavaScript code in an HTML.

When an HTML document gets loaded on a web browser that contains the SCRIPT element, the web browser process the content that is enclosed within the SCRIPT element as a JavaScript code.

JavaScript is a client-side scripting language that is developed by Netscape Communications Corporation, first released in May 1995.

We have two methods to add javascript to HTML.

1). inside HTML file in header section with “<script></script>” tag.

2). or you can create a separate javascript file and then link that file with HTML file.

Below are the example how we can do it using both ways:

Using Internal Javascript

How to write HTML JavaScript:-

1
2
3
4
5
6
7
8
9
10
11
<html>
<head>
<title> Javascript programming Language</title>
<script type=text/javascript”>
document.write(“<h1>hello, tutorialworld.in</h1>”);
</script>
</head>
<body>
<p>java script is a Client side scripting Language.</p>
</body>
</html>

HTML JavaScript Example of variable :-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<head>
<title> Javascript programming Language</title>
<script type=text/javascript”>
document.write(“<h1>hello, tutorialworld.in</h1>”);
var a=23,b=45,c;
c=a+b;
document.write(“The total of two variables”+c);
</script>
</head>
<body>
<p>java script is a Client side scripting Language.</p>
</body>
</html>

Using External Javascript

create a javascript file with extension .js, script.js

And write the Js code written below

1
2
3
function myFunction() {
  document.getElementById("change").innerHTML = "Paragraph changed.";
}

And one another HTML file with extension .html with content give below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>
<h2>This is the example of External JavaScript</h2>

<p id="change">General Paragraph.</p>

<button type="button" onclick="myFunction()">Click here</button>

<p>(myFunction is stored in an external file called "script.js")</p>

<script src="script.js"></script>

</body>
</html>

Advantage of External JavaScript

Below are the some example of external javascript

  • It allows us to separates HTML code with javascript code.
  • It makes HTML and JavaScript easier to read and maintain.
  • It provides us js caching.
  • It helps to get rid of painful web page loading time.

This tutorial was all about using javascript with HTML. And We have seen how we can do it in both ways internal JS embedding and external JS embedding. I have you have now cleared the concept of this topic. If you have any doubt feel free to ask.