How to Add JavaScript to Your HTML File

JavaScript – A programming language

JavaScript is the programming language of the web page which is used to update and change both HTML and CSS. It  is one of the “client-side scripting languages”, used to create interactive web-pages. It can also calculate, manipulate and validate data which is entered in the web page.
JS is used in several ways in web pages such as build image galleries, generate warning messages, DOM manipulation, validation form ,etc..

Adding JavaScript to HTML Pages

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

1.Embedding code

To add the JS code into an HTML pages, we can use the <script>…..</script> tag of the HTML which used to wrap around JS code inside the HTML program. Users can also define JavaScript code in the <body> tag or <head> tag .

<script>  
document.write("Learn JavaScript");  
</script>

2.Inline code

We can also add JavaScript directly in the html without using the <script>…. </script> tag. This method is used when we have to call a function in the HTML event attributes in which we have to add JS code directly such as OnMover event, OnClick, etc..

<!DOCTYPE html>  
<html>  
<head>  
<title> Javascript </title>  
</head>  
<body>  
<p>  
<a href="#" onClick="alert('Learn Javascript');">Click Here</a>  
</p>  
<p> add JavaScript directly in the html without using the <script>.... </script> tag </p>  
</body>  
</html>

3.External file

We can also create a separate file to create a JS code with the (.js) extension and include it into our HTML document using the src attribute of the <script> tag.

<html>  
<head>  
<meta charset="utf-8">  
<title> JS CODE </title>  
</head>  
<body>  
<form>
<H1> Learn Javascript </H1>    
<input type="button" value="Click Here to view message " onclick="display()"/>  
</form>  

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

</body>  
</html>
function display() {  
alert("JS is one of the client-side scripting languages");  
}

OUTPUT

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top