Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Adding JavaScript to HTML Pages

There are following three ways in which users can add JavaScript to HTML pages.

1. Embedding code
2. Inline code
3. External file

I. Embedding code:-
To add the JavaScript code into the HTML pages, we can use
the <script>.....</script> tag of the HTML that wrap around JavaScript code inside the
HTML program.

<!DOCTYPE html >


<html>
<head>
<title> page title</title>
<script>
document.write("Welcome to Javatpoint");
</script>
</head>
<body>
<p>Inthis example we saw how to add JavaScript in the head section </p>
</body>
</html>

II. Inline code:-


Generally, this method is used when we have to call a function in the HTML event
attributes. There are many cases (or events) in which we have to add JavaScript code
directly

<!DOCTYPE html >


<html>
<head>
<title> page title</title>
</head>
<body>
<p>
<a href="#" onClick="alert('Welcome !');">Click Me</a>
</p>
<p> in this example we saw how to use inline JavaScript or directly in an HTML ta
g. </p>
</body>
</html>

III. External file:-


We can also create a separate file to hold the code of JavaScript with the (.js) extension
and later incorporate/include it into our HTML document using the src attribute of
the <script> tag. It becomes very helpful if we want to use the same code in multiple
HTML documents. It also saves us from the task of writing the same code over and
over again and makes it easier to maintain web pages.

<html>
<head>
<meta charset="utf-8">
<title>Including a External JavaScript File</title>
</head>
<body>
<form>
<input type="button" value="Result" onclick="display()"/>
</form>
<script type="text/javascript" src="hello.js">
</script>
</body>
</html>

You might also like