< lang="en"> Client Side Scripting
× back

Client Side Scripting

Introduction to JavaScript

Features of JavaScript

Advantages and Disadvantages of JavaScript

Advantages

Disadvantages

Application of JavaScript

Including JavaScript along with HTML

JavaScript (JS) can be seamlessly integrated into HTML documents using various methods. Below are three commonly used approaches:

1: Placing JS code inside the body tag:

One method is to embed JavaScript directly within the body of the HTML document, typically at the end of the body tag. This allows the JavaScript code to access and manipulate the HTML elements on the page once they have been loaded. It's worth noting that when JavaScript code is placed here, the content of the webpage loads before the script is executed. This can be advantageous for ensuring that critical content is displayed to users before any JavaScript functionality is applied.

                        
<body>
    <!-- HTML content goes here -->

    <script>
        // JavaScript code here
        document.body.style.backgroundColor = "lightblue";
    </script>
</body>
                        
                    
2: Placing JS code inside the head tag:

Another approach is to include JavaScript within the head section of the HTML document. While this method is common, it's important to note that the JavaScript code is executed before the HTML content is parsed and loaded. This means that if JavaScript manipulates or interacts with HTML elements that have not yet been loaded, errors may occur.

                        
<head>
    <script>
        // JavaScript code here
        document.title = "Updated Title";
    </script>
</head>
                        
                    
3: Creating a separate external JS file:

Alternatively, JavaScript code can be placed in a separate external file with the ".js" extension. This file is then linked to the HTML document using the <script> tag. This method promotes code reusability and maintainability, as the same JavaScript file can be referenced by multiple HTML pages.

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

Variables and Data Types in JavaScript

JavaScript supports various data types and allows the creation of variables to store different kinds of information.

Declaring Variables:

Variables in JavaScript are declared using the var, let, or const keywords.

                        
// Using var
var x = 10;

// Using let (block-scoped)
let y = 'Hello';

// Using const (block-scoped, immutable)
const PI = 3.14;
                        
                    
Data Types:

JavaScript has several built-in data types:

  • Number: Represents numeric values, including integers and floating-point numbers.
  • String: Represents textual data enclosed within single or double quotes.
  • Boolean: Represents true or false values.
  • Array: Represents a collection of elements, which can be of any data type.
  • Object: Represents a collection of key-value pairs.
  • Undefined: Represents a variable that has been declared but not assigned a value.
  • Null: Represents the absence of any value.

Arrays in JavaScript

Array Literal Example:

            
// Creating an array using array literal
let emp = ["Arun", "Ayush", "Shaaer"];
for(i = 0; i < emp.length; i++)
{
    document.write(emp[i] + "<br/>")
}

            
        

Creating Instance of Array Directly Example:

            
let i;
let emp = new Array();
emp[0] = "Aman";
emp[1] = "Ayush";
emp[2] = "Anurag";
for(i = 0; i < emp.length; i++)
{
    document.write(emp[i] + "<br/>")
}
            
        

Using an Array Constructor Example:

            
let emp = new Array("Aman", "Anurag", "Ayush");
for(let i = 0; i < emp.length; i++)
{
    document.write(emp[i] + "<br/>")
}
            
        

Various Types of Arrays in JavaScript

In JavaScript, arrays are used to store multiple values in a single variable. They can hold different types of data and offer various functionalities for data manipulation.

1. Single-Dimensional Array

A single-dimensional array is the most common type of array in JavaScript. It contains a list of elements accessed by a single index.

Example: let numbers = [1, 2, 3, 4, 5];

2. Multi-Dimensional Array

A multi-dimensional array is an array of arrays, allowing for the creation of matrices or nested data structures.

Example: let matrix = [[1, 2], [3, 4], [5, 6]];

3. Array of Objects

An array of objects stores a collection of objects, each with its own properties and methods.

Example:

                        
let students = [
    { name: 'Alice', age: 20 },
    { name: 'Bob', age: 22 },
    { name: 'Charlie', age: 21 }
];
            
            

Operators and Expressions in JavaScript

JavaScript provides a variety of operators for performing operations on data, along with expressions that combine values and operators to produce a result.

Arithmetic Operators:

Arithmetic operators perform mathematical operations on numeric operands.

                        
// Addition
var sum = 5 + 3; // Result: 8

// Subtraction
var difference = 10 - 5; // Result: 5

// Multiplication
var product = 4 * 6; // Result: 24

// Division
var quotient = 20 / 4; // Result: 5

// Modulus (Remainder)
var remainder = 10 % 3; // Result: 1
                        
                    

Comparison Operators:

Comparison operators are used to compare values and return a boolean result.

                        
// Equal to
var isEqual = 5 === 5; // Result: true

// Not equal to
var notEqual = 10 !== 5; // Result: true

// Greater than
var greaterThan = 20 > 10; // Result: true

// Less than or equal to
var lessThanOrEqual = 3 <= 3; // Result: true
                        
                    

Logical Operators:

Logical operators are used to combine boolean values or expressions.

                        
var x = true;
var y = false;

// Logical AND
var resultAND = x && y; // Result: false

// Logical OR
var resultOR = x || y; // Result: true

// Logical NOT
var resultNOT = !x; // Result: false
                        
                    

Functions in JavaScript

Functions in JavaScript are reusable blocks of code that perform a specific task. They allow you to organize code, avoid repetition, and create modular programs.

Function Declaration:

A function declaration defines a named function.

                        
// Function Declaration
function greet(name) {
    return "Hello, " + name + "!";
}

// Calling the function
var greeting = greet("John"); // Result: "Hello, John!"
                        
                    

Function Expression:

A function expression defines a function as a variable assignment.

                        
// Function Expression
var multiply = function(a, b) {
    return a * b;
};

// Calling the function
var result = multiply(5, 3); // Result: 15
                        
                    

Arrow Function:

An arrow function is a concise way to write functions in JavaScript.

                        
// Arrow Function
var square = (num) => num * num;

// Calling the function
var squaredValue = square(4); // Result: 16
                        
                    

Function Parameters and Return:

Functions can accept parameters and return values.

                        
// Function with Parameters and Return
function add(a, b) {
    return a + b;
}

// Calling the function
var sum = add(10, 5); // Result: 15
                    
                

Common Built-in Functions:

JavaScript provides several built-in functions for common tasks.

                        
// parseInt
// Definition: Parses a string and returns an integer.
var num1 = parseInt("10"); // Result: 10

// parseFloat
// Definition: Parses a string and returns a floating-point number.
var num2 = parseFloat("3.14"); // Result: 3.14

// isNaN
// Definition: Checks if a value is NaN (Not a Number).
var isNumber = isNaN("Hello"); // Result: true

// typeof
// Definition: Returns the data type of a variable or expression.
var type = typeof(num1); // Result: "number"
                        
                    

Dialog Boxes in JavaScript

Dialog boxes are interactive elements used to display messages or prompts to users and collect input.

alert()

The alert() method displays an alert dialog with a specified message.

                        
alert("Hello, World!");
                        
                    

confirm()

The confirm() method displays a dialog box with a message and OK and Cancel buttons.

        
var result = confirm("Are you sure you want to delete this item?");
if (result) {
    // User clicked OK
} else {
    // User clicked Cancel
}
        
    

prompt()

The prompt() method displays a dialog box that prompts the user for input.

                        
var name = prompt("Please enter your name:");
if (name !== null) {
    alert("Hello, " + name + "!");
} else {
    alert("User cancelled the prompt.");
}
                        
                    
                                
<!DOCTYPE html>
<html lang="en">
<head>
<title>Voting Eligibility Checker</title>
</head>
<body>

<script>
        // Ask user for their age
        let age = prompt("Please enter your age:");

        // Convert age to a number
        age = parseInt(age);

        // Check if age is a valid number and greater than or equal to 18
        if (age >= 18) {
            alert("Congratulations! You are eligible to vote.");
        } else {
            alert("Sorry, you are not eligible to vote.");
        }

</script>

</body>
</html>
                                
                            
                                
<!DOCTYPE html>
<html lang="en">
<head>
<title>Addition Program</title>
</head>
<body>

<script>
        // Ask user for the first number
        let num1 = prompt("Enter the first number:");

        // Convert num1 to a number
        num1 = parseFloat(num1);

        // Ask user for the second number
        let num2 = prompt("Enter the second number:");

        // Convert num2 to a number
        num2 = parseFloat(num2);

        // Calculate the sum
        let sum = num1 + num2;

        // Display the result using alert
        alert("The sum of " + num1 + " and " + num2 + " is: " + sum);
</script>

</body>
</html>
                                
                            

Document Object Model (DOM)

Document Object

  • The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.
  • The Document object represents the entire HTML document in the DOM.
  • It provides properties and methods to access and manipulate various aspects of the document.
  • You can use the Document object to interact with elements, styles, events, and more within the document.
  • It is accessed through the global `document` variable in JavaScript.

Example: Accessing Document Properties

You can use the Document object to access properties like title, URL, and document type.

                            
// Get the document title
var pageTitle = document.title;

// Get the URL of the document
var pageURL = document.URL;

// Get the document type
var docType = document.doctype.name;
                            
                        

Example: Modifying Document Elements

The Document object allows you to modify elements, styles, and content within the document.

                            
// Create a new paragraph element
var newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";

// Append the new element to the document body
document.body.appendChild(newParagraph);

// Change the background color of the document body
document.body.style.backgroundColor = "lightblue";
                        
                    

Selecting Elements

Methods that help us select elements from the DOM:

getElementById

The getElementById method selects an element by its ID attribute.

                        
// Select an element by ID
var elementById = document.getElementById("myElementId");
                        
                    

getElementsByTagName

The getElementsByTagName method selects elements by their tag name.

                        
// Select elements by tag name
var elementsByTagName = document.getElementsByTagName("div");
                        
                    

getElementsByClassName

The getElementsByClassName method selects elements by their class name.

                        
// Select elements by class name
var elementsByClassName = document.getElementsByClassName("myClassName");
                        
                    
                                
<!DOCTYPE html>
<html>

<head>
    <title>Addition Program</title>
</head>

<body>
    <label>Num 1 : </label>
    <input type="text" id="t1"><br><br>
    <label>Num 2 : </label>
    <input type="text" id="t2"><br><br>
    <label>Sum Result : </label>
    <input type="text" id="t3"><br><br>
    <input type="button" value="Add" onclick="add()">
    <input type="button" value="Reset" onclick="reset()">
    <script>
        function add() {
            var num1 = parseInt(document.getElementById("t1").value);
            var num2 = parseInt(document.getElementById("t2").value);
            var sum = num1 + num2;
            document.getElementById("t3").value = sum;
        }
        function reset() {
            document.getElementById("t1").value = "";
            document.getElementById("t2").value = "";
            document.getElementById("t3").value = "";
        }
    </script>
</body>

</html>
                                
                            






                                
<!DOCTYPE html>
<html>

<head>
    <title>Factorial</title>
</head>

<body>
    <label for="">Enter a number : </label>
    <input type="text" id="t1"><br><br>
    <label for="">Factorial : </label>
    <input type="text" id="t2"><br><br>
    <input type="button" value="Find Factorial" onclick="fact()">
    <script>
        function fact() {
            var f = 1;
            var num = parseInt(document.getElementById("t1").value);
            for (var i = 1; i <= num; i++) {
                f = f * i;
            }
            document.getElementById("t2").value = f;
        }
    </script>
</body>

</html>
                                
                            




                                
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Factorial</title>
</head>

<body>
    <label for="">Enter A : </label>
    <input type="text" id="t1"><br><br>
    <label for="">Enter B : </label>
    <input type="text" id="t2"><br><br>
    <input type="button" value="Swap" onclick="swap()">
    <script>
        function swap() {
            var temp = parseInt(document.getElementById("t1").value);
            document.getElementById("t1").value = document.getElementById("t2").value;
            document.getElementById("t2").value = temp;
        }
    </script>
</body>

</html>
                                
                            




Form Validation

We can apply validation using the following methods:

  1. HTML 5: This method is easier as we can use attributes like 'required' for simple validations directly in HTML tags.
  2. jQuery: This approach, although deprecated now, was based on JavaScript and allowed for more interactive form validation.
  3. JavaScript: This method is superior as it provides more control and flexibility. Using JavaScript, we can handle complex validations, customize error messages, and implement dynamic validation logic based on user inputs.

                                
<!DOCTYPE html>
<html>
<body>
    <form action="#" name="myform">
        <label>Name : </label>
        <input type="text" name="name" /> <br><br>
        <label>Password : </label>
        <input type="password" name="password" /> <br><br>
        <input type="button" value="submit" onclick="validate()" />
        <input type="reset" value="reset">
    </form>
    <script>
        function validate() {
            var name = document.myform.name.value;
            var password = document.myform.password.value;
            if (name == "") {
                alert("Name can't be blank!");
            }
            else if (password.length < 6) {
                alert("Password must be atleast 6 characters long!");
            }
        }
    </script>
</body>
</html>
                                
                            




                                
<!DOCTYPE html>
<html>
<body>
    <form action="#" name="myform" onsubmit="validate()">
        <label>Number : </label>
        <input type="text" name="num" /> <br>
        <span id="numloc"></span>
        <br>
        <input type="submit" value="submit">
    </form>
    <script>
        function validate() {
            var num = document.myform.num.value;
            if (isNaN(num)) {
                document.getElementById("numloc").innerHTML = "Enter numberic value only";
            } else {
                document.getElementById("numloc").innerHTML = "";
            }
        }
    </script>
</body>
</html>
                                
                            


  • We have used the `isNaN()` function, which checks if a value is not a number (NaN). In our validation logic, `isNaN(num)` is used to verify if the input value in the "num" field is a numeric value or not. If it's not a number, the validation displays an error message.
  • We have also used `.innerHTML`, which is a property that allows us to get or set the HTML content inside an element. In our validation function, `document.getElementById("numloc").innerHTML` is used to dynamically update the content of the `<span>` element with the ID "numloc" to display the error message when the input value is not a number.

Design a page using the following JS constraints:
1- Validate a field against an email address.
2- Validate a field against alphanumeric values.
3- Validate a field against a minimum length of 6 characters and a maximum length of 15 characters.

                                
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
    <h2>Form Validation</h2>
    <form id="myForm">
        <label for="email">Email Address:</label>
        <input type="text" id="email" name="email"><br>

        <label for="alphanumeric">Alphanumeric Field:</label>
        <input type="text" id="alphanumeric" name="alphanumeric"><br>

        <label for="length">Length Field (6-15 characters):</label>
        <input type="text" id="length" name="length"><br>

        <input type="button" value="Submit" onclick="validateForm()">
    </form>
    <script>
        function validateForm() {
            const email = document.getElementById('email').value;
            const alphanumeric = document.getElementById('alphanumeric').value;
            const lengthField = document.getElementById('length').value;
            const emailPattern = /^[A-Za-z\._\-0-9]*[@][A-Za-z]*[\.][a-z]{2,4}$/;
            const alphanumericPattern = /^[a-zA-Z0-9]*$/;

            let isValid = true;

            // Validate Email
            if (!email.match(emailPattern)) {
                alert('Please enter a valid email address.');
                isValid = false;
            }

            // Validate Alphanumeric
            if (!alphanumeric.match(alphanumericPattern)) {
                alert('Please enter only alphanumeric characters.');
                isValid = false;
            }

            // Validate Length
            if (lengthField.length < 6 || lengthField.length > 15) {
                alert('Length must be between 6 and 15 characters.');
                isValid = false;
            }

            // If all validations pass
            if (isValid) {
                alert('Form submitted successfully!');
                // Here you can add further actions, such as sending form data to a server or redirecting to another page.
            }
        }
    </script>
</body>
</html>
                                
                            

Email Validation Regular Expression Explanation

The regular expression /^[A-Za-z\._\-0-9]*[@][A-Za-z]*[\.][a-z]{2,4}$/ is used for validating simple email addresses. Here's a detailed breakdown of each part of the pattern:

  • /: The starting delimiter for the regular expression.
  • ^: Anchors the pattern to the start of the string. Ensures that the match starts at the beginning of the string.
  • [A-Za-z\._\-0-9]*: Matches zero or more characters that can be:
    • A-Z: Any uppercase letter.
    • a-z: Any lowercase letter.
    • \.: A literal dot (the backslash \ is used to escape the dot, as dot is a special character in regex that matches any character).
    • _: A literal underscore (no need to escape, as underscore has no special meaning in regex).
    • \-: A literal hyphen (escaped with \ to distinguish from range indicator in character class).
    • 0-9: Any digit.

    The * quantifier matches zero or more occurrences of the preceding element, allowing for flexibility in the number of characters in this part of the email address.

  • [@]: Matches exactly one "@" symbol.
  • [A-Za-z]*: Matches zero or more uppercase or lowercase letters.

    The * quantifier here also allows for flexibility in the number of characters in this part of the email address.

  • [\.]: Matches exactly one dot (escaped with \ to treat it as a literal character).
  • [a-z]{2,4}: Matches 2 to 4 lowercase letters (the domain extension, such as "com", "org", "net").
  • $: Anchors the pattern to the end of the string. Ensures that the match ends at the end of the string.
  • /: The ending delimiter for the regular expression.

This regular expression ensures that the email address:

  • Starts with letters, dots, underscores, hyphens, or digits.
  • Contains exactly one "@" symbol.
  • Has letters for the domain name before the dot.
  • Contains a dot followed by a domain extension of 2 to 4 lowercase letters.

Example of valid email addresses:

  • user@example.com
  • john_doe@example.net
  • name123@example.org

Example of invalid email addresses:

  • userexample.com (missing "@")
  • john.doe@ (missing domain part)
  • name@domain.c (domain extension too short)
  • name@domain.company (domain extension too long)

JavaScript Events and Event Handling

Types of JavaScript Events:

HTML Events and Their Event Handlers

Example

Keep Mouse Over me

                            
<!DOCTYPE html> 
<html> 
    <body>
        <p onmouseover="mouseOverEventHandler()"> Keep Mouse Over Me </p> 

        <script>
            function mouseOverEventHandler()
            {
                alert("Mouse Over Event Executed!!")
            }
        </script> 
    </body>
</html>
                            
                        
                            
<!DOCTYPE html> 
<html> 
    <body>
        <label>Input : </label>
        <input type="text" id="t1" onfocus="focusEventHandler()" /> 

        <script>
            function focusEventHandler()
            {
                document.getElementById("t1").style.background = "red";
            }
        </script> 
    </body>
</html>