Home Web DevelopmentHTML How to Add and Link JavaScript to HTML

How to Add and Link JavaScript to HTML

Introduction

Html creates static web pages, but as users, we want highly responsive web pages that improve our user experience and provide dynamic functionality. We need real-time interaction with the webpages such as alert messages, animations, popups, etc; this can only be achieved by linking Javascript to HTML.

With that said, we can ask ourselves what is JavaScript in terms of web development. Javascript is a front-end web scripting language that provides dynamic functionality and interactive web pages. JavaScript adds some presentation features to HTML documents.

Advantages of adding Javascript in an HTML document

Lets look at some of the advantages of adding JavaScript into Html.

Richer and user-friendly interface

With JavaScript, you can create interactive, user-friendly interfaces. Interfaces that allow a user to have a real-time interaction such as, on click of a button it pops up a message, adding sliders, mouse rollover effects, and so on.

Immediate feedback to the user

Since JavaScript can be used without refreshing a page, it can give immediate feedback to the user. For example, in form validation, if a user leaves one of the fields empty before sending the data to the server, JavaScript validates and reports back immediately.

Example of Javascript form validation:

<!DOCTYPE html>
<html>
<head>
	<title>sign up</title>
	<style type="text/css">
		body{
	background-color: lightblue;
	padding: 0;
	margin: 0;
}
#wrapper{
	width: 900px;
	background-color: white;
	margin: 0px auto;
	min-height: 400px;
	border: 1px solid black;
	margin-top: 40px;
	border-radius: 5px;}
#form{
	margin: 0px auto;
	width: 210px;
	margin-top: 10px;}
	</style>
	<script type="text/javascript">
		  function checkForm(form)
  {
    if(sign.f_name.value == "") {
      alert("Error: First Name cannot be blank!");
      sign.f_name.focus();
      return false;
    }
    re = /^\w+$/;
    if(!re.test(sign.f_name.value)) {
      alert("Error: First Name must contain only letters, numbers and underscores!");
      sign.f_name.focus();
      return false;
    }
	
    if(sign.lname.value == "") {
      alert("Error: Last Name cannot be blank!");
      sign.lname.focus();
      return false;
    }
	re = /^\w+$/;
    if(!re.test(sign.lname.value)) {
      alert("Error: Last Name must contain only letters, numbers and underscores!");
      sign.lname.focus();
      return false;
    }
    if(sign.email.value == "") {
      alert("Error: Email cannot be blank!");
      sign.lname.focus();
      return false;
    }
    if(sign.password.value != "" && sign.password.value == sign.confirm_pass.value) {
      if(sign.password.value.length < 6) {
        alert("Error: Password must contain at least six characters!");
        sign.password.focus();
        return false;
      }
      if(sign.password.value == sign.f_name.value) {
        alert("Error: Password must be different from Username!");
        sign.password.focus();
        return false;
      }
      re = /[0-9]/;
      if(!re.test(sign.password.value)) {
        alert("Error: password must contain at least one number (0-9)!");
        sign.password.focus();
        return false;
      }
      re = /[a-z]/;
      if(!re.test(sign.password.value)) {
        alert("Error: password must contain at least one lowercase letter (a-z)!");
        sign.password.focus();
        return false;
      }
      re = /[A-Z]/;
      if(!re.test(sign.password.value)) {
        alert("Error: password must contain at least one uppercase letter (A-Z)!");
        sign.password.focus();
        return false;
      }
    } else {
      alert("Error: Please check that you've entered and confirmed your password!");
      sign.password.focus();
      return false;
    }
    alert("You entered a valid password: " + sign.password.value);
    return true;
  }
	</script>
</head>
<body>
<div id="wrapper">
<div id="form">
<form action="" method="Post" name="sign" id="sign" ... onsubmit="return checkForm(this);">
<fieldset>
<legend>FORM VALIDATION EXAMPLE</legend>
<label>first Name:</label><br>
<Input type="text" name="f_name"  onkeypress="validate()"/></br></br>
  
<label>last Name:</label><br>
<Input type="text" name="lname"><br></br>

<label>email:</label><br>
<input type="text" name="email"><br><br>

<label>password:</label><br>
<Input type="password" name="password" ><br></br>

<label>re-enterPassword:</label><br>
<Input type="password" name="confirm_pass"><br></br>

<input type="submit" name="submit" onclick="validate()"><br>

</fieldset>
<br>
</form>
</div>
</div>
</body>
</html>

Minimalized server interaction

JavaScript helps reduce the usage of server resources and the number of requests to the server when used in form validation. It’s also swift since it provides immediate response.

Methods to link and add Javascript into HTML

There are three ways to do this.

  • Embedding code
  • Inline code
  • External linking

Lets discuss each one of them.

Embedding code

This includes adding your JavaScript between the <script> and </script> tag. The <script> indicates to the browser that the contained statements are to be interpreted as executable script and not as HTML. There are two ways of embedding JavaScript into HTML using <script>.

Between the <head> tag

If we want the script to be run before the page contents are rendered, we add JavaScript between the <head> and </head> tag.
Example: Let’s display a greeting message “Good Morning, Arise and shine” through a JavaScript alert command before or at the time of page loading.

<!DOCTYPE>
<html >
  <head>
    <title> THE PAGE SAYS GOOD MORNING </title>
    <script type="text/javascript">
    window.onload = function() 
    {
     alert('Good Morning, Arise and shine');
   };
    </script>
  </head>
  <body>
 
    <h4>On load the page says Good Morning, Arie and shine</h4>
  </body>
</html

Before or after the body closing tag

Before the </body>

Here we want the script to run after the contents of the page are rendered. Ideally its good to place the <script> tag just before the </body>.This makes the web pages load more quickly as there is the prevention of obstruction of initial page rendering.

<!DOCTYPE html>
<html>
<head>
  <title>Body</title>
</head>
<body>
  <p> Javascript Before the body closing tag </p>  
 <script>  
    document.write("Good Bye Javascript");  
    </script>     
</body>
</html>
After the body closing tag (</body>)
<!DOCTYPE html>
<html>
<head>
  <title>Body</title>
</head>
<body>
  <p> Javascript After the body closing tag </p>     
</body>
<script>  
    document.write("Good Bye Javascript");  
    </script>  
</html>

Inline code

This involves inserting the JavaScript directly inside the HTML tags using special tag attributes such as Onclick, on mouseover, Onkeypress, Onload, and so on.
Placing a large amount of Javascript code inline deteriorates the ability to debug your code and make it difficult to maintain.

 <!DOCTYPE html>
<html>
<head>
  <title>Javascript</title>
</script>
</head>
<body>
<h1>The onclick Event, clicking the button the pages displays welcome message</h1>
<button onClick="alert('Welcome !');">Click Me!</button>
</body>
</html>

External File

This involves creating an external separate file with a .js extension to hold the Javascript code and then linking it to your HTML document using the src attribute of the <script> tag.

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

When an external JavaScript file is downloaded for the first time, it is stored in the browser’s cache. This increases the web pages loading speed since the JavaScript won’t be downloaded multiple times.

Advantages of using external JavaScript

  • Helpful when you want to use the same code in multiple HTML documents. This saves the hassle of rewriting the same code over and over again.
  • Increases the loading speed since external Javascript files are cached on the first load.
  • Placing javascript external is a good practice since it makes it easier to maintain the web pages.
<!DOCTYPE html>
<html>
<head>
  <title>External Javascrip</title>
  <script type="text/javascript" src="script.js"></script> 
</head>
<body>
   <form>  
    <input type="button" value="Click to View External Javascript" onclick="display()"/>  
    </form>  
</body>
</html>

Now lets create the external javascript file

   function display() {  
    alert("I am an external javascript, Thank you for loading me!");  
    }  

Output

External

The 3 ways to load an external JavaScript file

Normal loading

The HTML document is loaded to the page until there is an instance occurrence of JavaScript. In that case, the HTML is paused, and the JavaScript is executed, and then the rest of the HTML will continue being rendered.

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

In this case, the JavaScript is asynchronously downloaded alongside the HTML file. The after the script is completed, it’s executed, and then the browser continues parsing the HTML document. We load javascript asynchronously when we do not have any dependencies.

<script src="script.js" async></script>
Defer its loading

In this case the JavaScript is paused from loading until the HTML document is loaded completely.

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

Javascript as a link

As we know, links create a reference or hyperlinks to other sections of the webpage. On clicking a link, an action is fired according to the link reference. We can also use JavaScript with the anchor tag <a>, then we call the JavaScript action to be performed instead of putting the link. In that case, the JavaScript will be used as a link. There are two ways to do this, which both of them achieve the same thing.

  • By using javascript:;
  • By use of javascript: void(0)

Example

<!DOCTYPE html>
<html>
<head>
  <title>Javascript as a link</title>
</head>
<body>
<a href="JavaScript:void(0);" onclick="alert('Well done! Method 1 test case')">Click me! Test 1</a><br><br>
  
<a href="JavaScript:;" onclick="alert('Well done! Method 2 test case')">Click Me! Test 2</a>
</body>
</html>

Conclusion

Were you worried about how you can add and link JavaScript into HTML documents? Well, I believe this article has been of high benefit to you in deciding the best method to use. In case of any question, please leave in the comment section below. I will be glad to help! Happy Learning!

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More