Basics of JavaScript: Part 2

Introduction

The previous part explained the purpose of using JavaScript

This article discusses the following topics,

  1. Inline and external JavaScript.
  2. Advantages of external JavaScript over inline JavaScript.
  3. Where the script tag should be placed.

JavaScript can be stored inline on the page or in an external JavaScript (.js) file.

First, let's see how to create an Inline JavaScript.

Inline JavaScript

The first step is to create a user interface that looks like this.

https://www.c-sharpcorner.com/topics/html

The following is the HTML required for creating the preceding UI,

<!DOCTYPE html>    
<head>    
    <title>Inline JavaScript</title>    
</head>    
<body>    
    <form>    
        <p>Enter Number:     
            <input type="text" name="txtOne" id="txtOne">    
            </p>    
            <input type="submit" value="Validate"/>    
        </form>    
    </body>    
</html> 

Now what we want is, we want to add functionality using which we will be able to check if the input is a valid number or not. If the user enters a number and clicks the button, we want to display an alert box stating the number is valid. Otherwise, if the user enters some literal text, we want to display an alert box requesting that a good number be entered. So, let's see how to do that.

Write the following in the head section.

<head>    
    <title>Inline JavaScript</title>    
    <!--to add a javascript we use script tag where we pass the text/javascript as the script type-->    
    <script type="text/javascript">    
//to create a function we use function keyword and name of the function    
//here ValidateInput is the function name. The parameters are optional    
function ValidateInput()    
{    
//to get the html element based on an Id we can use document.getElementById('ElementId')    
var number = document.getElementById('txtOne').value;//retrieving the value    
//to check if an input is number of or we use isNaN function    
if (!isNaN(number))     
{    
alert(number + ' is a valid number');    
}    
else    
{    
alert('Please enter a valid number');    
}    
}    
</script>    
</head>   

Pass the function name in the button's onclick event.

<input type="submit" value="Validate" onclick="ValidateInput()"/>   

Open the file in a browser.

Pass a string and click Validate.

https://www.c-sharpcorner.com/topics/html

Since g is not a number, we got the alert box stating, "Please enter a valid number."

Now specify a valid number and click Validate.

https://www.c-sharpcorner.com/topics/html

Now let's see how to use an external js file.

External JavaScript

The first step is to create a file with an extension of .js, and inside that JavaScript file, add the following JavaScript code.

function ValidateInput()    
{    
    var number = document.getElementById('txtOne').value;    
if (!isNaN(number))     
{    
    alert(number + ' is a valid number');    
}    
else    
{    
    alert('Please enter a valid number');    
}    
}  

In the HTML document, we need to specify the source of the JavaScript file using the script tag's src attribute.

<head>    
<title>Untitled Document</title>    
<script src="script.js" type="text/javascript"></script>    
</head>  

Save and open the file in the browser.

https://www.c-sharpcorner.com/topics/html

https://www.c-sharpcorner.com/topics/html

Advantages of using External JavaScript over Inline JavaScript

Maintainability

External JavaScript files can be used on multiple pages without duplicating the code inline on every page. If there is a requirement to change anything, you only have one place to change.

Performance

An external JavaScript file can be cached by the browser, whereas an inline JavaScript on the page is loaded every time the page loads.

Separation

It is a good practice to separate HTML, CSS, and JavaScript since it makes it easier to work with them.

Script tag in HTML

  • Where should the script tag be placed in HTML? Inside the body or in the head section.
  • In general, it can be placed either in the head or body sections.
  • Let's look at some examples where we will place the script tag in the head and the body section.

Example 1

<html>    
    <head>    
        <title></title>    
        <script type="text/javascript">    
alert('Basics of javascript');    
</script>    
    </head>    
    <body></body>    
</html>   

In the preceding example, we have passed the script element in the head section.

Open the file in the browser.

https://www.c-sharpcorner.com/topics/html

Now let's move the script element to the body section.

<html>    
    <head>    
        <title></title>    
    </head>    
    <body>    
        <script type="text/javascript">    
alert('Basics of javascript');    
</script>    
    </body>    
</html>   

Open the file in a browser.

https://www.c-sharpcorner.com/topics/html

We got the same output.

Example 2

There are some scenarios where when we place the script tag in the body section, it will work, but it will not work in the head section.

First, remove the script tag from the body section and add a textbox control to your form.

<html>    
    <head>    
        <title></title>    
    </head>    
    <body>    
        <form>    
            <input type="text" id="txtOne"/>    
        </form>    
    </body>    
</html> 

https://www.c-sharpcorner.com/topics/html

Now what we want here is whenever this page is loaded, we want to change the background color of the preceding textbox control to Yellow.

Write the following JavaScript code after the closing form tag.

<script type="text/javascript">    
document.getElementById('txtOne').style.backgroundColor = 'yellow';    
</script>   

Open the File in a browser.

https://www.c-sharpcorner.com/topics/html

Now let's see how to do the same by shifting the script element to the head section.

<html>    
    <head>    
        <title></title>    
        <script type="text/javascript">    
document.getElementById('txtOne').style.backgroundColor = 'yellow';    
</script>    
    </head>    
    <body>    
        <form>    
            <input type="text" id="txtOne"/>    
        </form>    
    </body>    
</html>   

Open the file in the browser.

https://www.c-sharpcorner.com/topics/html

Look at the output we got. The background color of the textbox did not change to Yellow.

So, why did the JavaScript not work in this case?

Our JavaScript code is present before the textbox control. When the JavaScript code is executed, the textbox is still not loaded into the browser's document object model. This is the reason JavaScript can't find the textbox.

Summary

This article discussed where we could add JavaScript and its advantages. We also discussed where the script tag should be placed in an HTML file.

I hope you like it

Thank you.


Similar Articles