lang="en">
JavaScript (JS) can be seamlessly integrated into HTML documents using various methods. Below are three commonly used approaches:
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>
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>
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>
JavaScript supports various data types and allows the creation of variables to store different kinds of information.
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;
JavaScript has several built-in data types:
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/>")
}
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.
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];
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]];
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 }
];
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 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 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 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 are reusable blocks of code that perform a specific task. They allow you to organize code, avoid repetition, and create modular programs.
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!"
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
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
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
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 are interactive elements used to display messages or prompts to users and collect input.
The alert() method displays an alert dialog with a specified message.
alert("Hello, World!");
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
}
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>
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;
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";
Methods that help us select elements from the DOM:
The getElementById
method selects an element by its
ID attribute.
// Select an element by ID
var elementById = document.getElementById("myElementId");
The getElementsByTagName
method selects elements by
their tag name.
// Select elements by tag name
var elementsByTagName = document.getElementsByTagName("div");
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>
We can apply validation using the following methods:
<!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>
<!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>
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:
Example of valid email addresses:
Example of invalid email addresses:
Types of JavaScript Events:
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>