This tutorial aims to guide you about the “JavaScript use in HTML” as it describes

  • How you are able to add JavaScript to HTML and
  • What the different ways of using JavaScript to HTML are?

Generally, when we talk about the HTML, the first conception comes in our mind is it is best for developing the static web pages containing a set of images etc. But in these modern times, it’s not enough just to show static information to the user. It’s the age where we need the most interactive contents in our web pages that contain forms, flashy slideshows, and menus to attract the user. These interactive contents enable us to add dynamic behavior on our websites that enhance the experience of the user most.

To add dynamic contents in web pages, JavaScript is a powerful scripting language for this purpose. It enables the developers to create interactive websites that respond to the user at runtime and make it user-friendly. There exist many languages for dynamic website development but JavaScript considered more powerful and popular scripting language than others. It is widely used with HTML in order to get its advantages to a great extent.

Advantages of JavaScript

In the beginning, JavaScript is known as LiveScript due to its interactive capability. But as Java becomes more popular and worldly known language so Netscape renames it with JavaScript. Firstly it was introduced in 1995 by Netscape 2.0.

Here some advantages which we can achieve by using JavaScript:

Server interaction requirement reduced

By using JavaScript, you can reduce the server interaction as we can achieve the optimized performance of a website by reducing the communication with the server. JavaScript is capable of doing the user validation at client side rather than at the server side. It runs an initial verification code at a client computer and then passes the request to the server for more validation checks. Due to initial validation checks at a client side, the

Better-off, comprehensible & user-friendly interfaces

JavaScript is well known for providing the attractive and user-friendly interfaces. You can create slideshows, mouse rollover effects, drag-and-drop features etc. for the interactive and user-friendly interface.

Quick Responses to the user

JavaScript provides quick responses to the user as it performs initial validation checks at the client side. It shows the response for any of invalid input quickly at that instant without reloading the page again.

Easy debugging

The interpreter used in JavaScript which ensures the error found and corrected immediately as it performs line by line execution of code. You are able to trace the location of error immediately.

Adding JavaScript to HTML

Two well-known ways exists to add JavaScript to HTML to achieve its best advantage  for the development of dynamic website which are

  1. Adding JavaScript directly to a HTML file
  2. Adding JavaScript code to a separate file

These ways are discussed in detail below.

  1. Adding JavaScript directly to a HTML file

In order to add JavaScript to HTML, firstly we add the script tags.

  • At the start of JavaScript code write <script>
  • At the end of JavaScript code write </script>

All statement of JavaScript code must be written between these tags. JavaScript code can be written at two places:

  • between the <head> and </haed> tags
  • between the <body>  and </body> tags

Loading will differ when we add JavaScript code at these two places. As performance matter a lot in interactive interfaces, we must care for quick loading of web pages at client side. By placing the JavaScript code between the <body> and </body> tags, we increase the loading speed as the actual website content will be loaded quicker.

Example: Here is code to show the current time.

<!DOCTYPE html>
<htmllang="en-US">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1">
<script>JAVASCRIPT HERE</script>
<title>Time right now is: </title>
</head>
<body>
<script>JAVASCRIPT CAN ALSO ADD HERE</script>
</body>
</html>

 

At present, JavaScript is not involved in the above code and due to this reason, actual time cannot be shown. In order to show the actual time, we can add the following code.

var time =new Date();
log(time.getHours()+":"+time.getMinutes()+":"+time.getSeconds());

 

This code is written between <script> and </script> tags and place in between< head> and </head> tags of HTML file. The code shows the current time when the page loads. After adding the code ,HTML file looks like:

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Time right now is: </title>
<script>
var time = new Date();
log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
</script>
</head>
<body>
</body>
</html>

 

In order to show the time within the page body, the code must be written between the <body> and </body> tags. The code looks like after adding the code within the body of an HTML page.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Time right now is: </title>
</head>
<body>
<script>
let d = new Date();
body.innerHTML = "<h1>Time right now is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()
"</h1>"
</script>
</body>
</html>

Final result of the code looks like as:

Adding JavaScript code to a separate file

The idea of adding JavaScript to a separate file comes due to the need of JavaScript use on multiple pages. We use JavaScript in a separate file just like cascading style sheet. JavaScript code external file imported in HTML file to access the code. JavaScript in a separate file offers the following benefit:

  • Separation of HTML and JavaScript code makes the web pages easy to reuse and maintainable. It supports the design principle of separation of Concern.
  • Code readability and maintenance is made a lot easier.
  • Separation of HTML and JavaScript code makes it more readable and sustainable.
  • In General website performance will be improved due to Cached JavaScript file by reducing the time taken by pages to load.

Referenced JavaScript file within HTML written as:

<!DOCTYPE html>
<htmllang="en-US">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width, initial-scale=1">
<title>Current Time:</title>
</head>
<body>
</body>
<scriptsrc="js/myscript.js"></script>
</html>

The subjects of the myscript.js file written as:

let d = new Date();
body.innerHTML = "<h1>Time right now is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()</h1>"

 

For this code, it is assumed that myscript.js file placed in the same directory in which HTML file exist.

Email validation Example by using JavaScript

By using JavaScript, you are able to perform initial validation checks at client side. Most often a requirement of validation is at the time of entering email address by the user. Following JavaScript function helps to validate the email address before sending it to the server.

functionvalidateEmailAddress(email){
var re =/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
returntest(email);
}
function validate(){
$("#result").text("");
varemailaddress= $("#email").val();
if(validateEmailAddress(emailaddress)){
$("#result").text(emailaddress+" is valid :)");
$("#result").css("color","green");
}else{
$("#result").text(emailaddress+" not correct, try again:(");
$("#result").css("color","red");
}
returnfalse;
}
$("#validate").bind("click", validate);

In order to attach this function to a form input, you can use the following code:

<form>
<p>Enter an e-mail:</p>
<input id='email'>
<button type='submit' id='validate'>Check!</button>
</form>
<h2 id='result'></h2>

The result is given below of the JavaScript and Html code:

Incorrect Validation produce different results than correct result

Final Word

This article is about the two ways of adding JavaScript in HTML code and you can do great things by combining these two languages.  Modern and interactive web applications can be developed by using these two languages. By combining these languages, we can create user-friendly interfaces. It provides the minimum server communication by performing the validation process at the client side that improves the performance and efficiency of the website.

Leave a Reply