Unit 3: Client Side Programming with JavaScript
By Notes Vandar
3.1 How JavaScript fits into a web page?
JavaScript is a client-side scripting language that enhances the interactivity, functionality, and behavior of a web page. Unlike HTML, which defines the structure and content, and CSS, which controls the presentation, JavaScript enables dynamic content and interaction within the browser.
There are three main ways JavaScript fits into a web page:
1. Embedding JavaScript Inline within HTML
JavaScript can be embedded directly inside an HTML document using the <script>
tag. The script can be placed either in the <head>
or <body>
section of the HTML document, depending on when you want the JavaScript code to run.
Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>JavaScript Inline Example</title>
<script>
// Inline JavaScript
function greet() {
alert(‘Hello, welcome to the website!’);
}
</script>
</head>
<body>
<h1>JavaScript in an HTML Page</h1>
<button onclick=”greet()”>Click Me</button>
</body>
</html>
Explanation:
- The JavaScript function
greet()
is defined within the<script>
tag in the<head>
section. - The
onclick="greet()"
event in the<button>
element triggers the function when the button is clicked, displaying an alert.
Key Points:
- Positioning: Scripts in the
<head>
run before the page is fully loaded, while scripts in the<body>
run as the page is loaded. - Inline usage is simple and works well for small bits of JavaScript, but it can make the page harder to maintain if the script grows larger.
2. Linking External JavaScript Files
JavaScript is typically placed in external files (.js
files), which are linked to the HTML document using the <script>
tag. This is a best practice for separating content (HTML), presentation (CSS), and behavior (JavaScript).
Example:
<!– HTML file –>
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>External JavaScript Example</title>
<script src=”script.js” defer></script> <!– Linking an external JavaScript file –>
</head>
<body>
<h1>JavaScript in an External File</h1>
<button onclick=”greet()”>Click Me</button>
</body>
</html>
function greet() {
alert(‘Hello, welcome to the website!’);
}
Explanation:
- The
<script src="script.js" defer></script>
tag in the<head>
links to an external JavaScript file,script.js
. - The
defer
attribute ensures that the script runs after the HTML document is fully parsed, improving load performance. - External JavaScript files allow you to reuse code across multiple HTML pages and keep your code organized.
Key Points:
- External scripts improve code maintainability and reusability, especially for larger projects.
- Loading: External files can be loaded asynchronously (
async
) or deferred (defer
) to optimize page performance.
3. JavaScript in the Body (Event-Driven Behavior)
JavaScript can also be placed in the <body>
of an HTML document to control the behavior of the page and respond to user interactions. You can use event handlers such as onclick
, onmouseover
, onload
, etc., to execute JavaScript code in response to specific actions.
Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>JavaScript Events</title>
</head>
<body>
<h1>JavaScript with Event Handlers</h1>
<button id=”myButton”>Click Me</button>
<script>
// JavaScript code inside the body
document.getElementById(‘myButton’).addEventListener(‘click’, function() {
alert(‘Button was clicked!’);
});
</script>
</body>
</html>
Explanation:
- JavaScript is added at the bottom of the
<body>
to ensure the HTML elements are loaded before the script runs. - The
addEventListener()
method attaches aclick
event to the button and triggers an alert when clicked.
Key Points:
- Event-driven scripting: JavaScript works well when responding to user interactions, such as clicks, form submissions, or mouse movements.
- Improved user experience: Dynamic behavior through events enhances user interactivity.
Loading JavaScript with Best Practices
There are two common attributes that control when and how JavaScript is loaded to optimize performance:
defer
:- Ensures the script is executed only after the HTML document has been fully parsed.
- The script is loaded asynchronously but executed in the order they appear in the document.
- Ideal for non-blocking, DOM-related scripts.
<script src=”script.js” defer></script>async
:- Loads the script asynchronously, but the script is executed as soon as it’s downloaded.
- Scripts are executed without waiting for other scripts to finish, making it non-sequential.
- Suitable for non-DOM related scripts like analytics.
<script src=”analytics.js” async></script>
How JavaScript Interacts with the DOM
JavaScript interacts with the Document Object Model (DOM), which is the structured representation of the HTML document. JavaScript can:
- Manipulate elements: Create, modify, or remove HTML elements dynamically.
- Style elements: Change CSS styles on the fly.
- Handle user input: Respond to user interactions like form submissions, clicks, and more.
Example of JavaScript Manipulating the DOM:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>DOM Manipulation</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<h1 id=”title”>Hello, World!</h1>
<button id=”highlightButton”>Highlight Text</button>
<script>
document.getElementById(‘highlightButton’).addEventListener(‘click’, function() {
document.getElementById(‘title’).classList.toggle(‘highlight’);
});
</script>
</body>
</html>
Explanation:
- The JavaScript toggles the
highlight
CSS class when the button is clicked, which dynamically changes the background color of the title
3.2 JavaScript Basics: Variables and Operators
In JavaScript, variables and operators form the foundation of the language, allowing you to store data and perform various operations. Understanding these basics is essential for writing any JavaScript code.
3.2.1 Variables in JavaScript
Variables are used to store data values that can be referenced and manipulated in a JavaScript program. Variables can hold different data types such as numbers, strings, objects, etc.
Declaring Variables
In JavaScript, you declare a variable using the var
, let
, or const
keywords. Each has its own characteristics:
var
: Declares a variable with function or global scope (depending on where it’s declared).let
: Declares a block-scoped variable, which is more suitable for modern JavaScript.const
: Declares a block-scoped variable that cannot be reassigned after its initial declaration (although the value itself can be mutable, like in arrays and objects).
Syntax:
// Using var
var x = 10; // Global or function-scoped
// Using let
let y = 20; // Block-scoped (limited to a specific code block)
// Using const
const z = 30; // Block-scoped and cannot be reassigned
Rules for Variable Names:
- Must start with a letter, underscore (
_
), or dollar sign ($
). - Can contain letters, numbers, underscores, or dollar signs.
- Are case-sensitive (e.g.,
myVar
andmyvar
are different variables).
Example:
const age = 25; // Number value
var isStudent = true; // Boolean value
3.2.2 Data Types in JavaScript
JavaScript supports various data types:
- Primitive Types:
- String: Text data (
"Hello"
,'World'
). - Number: Numeric data (
42
,3.14
). - Boolean: Logical true/false values (
true
,false
). - Null: Represents a deliberate non-value (
null
). - Undefined: Variables that are declared but not initialized (
undefined
). - Symbol: Unique and immutable identifier (rarely used).
- String: Text data (
- Non-primitive Types:
- Object: Collections of key-value pairs (
{name: "Alice", age: 30}
). - Array: Ordered collections of values (
[1, 2, 3]
).
- Object: Collections of key-value pairs (
3.2.3 Operators in JavaScript
Operators in JavaScript are used to perform various operations on values and variables. They can be categorized into several types:
1. Assignment Operators
Assignment operators are used to assign values to variables.
=
: Assigns the value to a variable.+=
: Adds and then assigns the result.-=
: Subtracts and then assigns the result.*=
: Multiplies and then assigns the result./=
: Divides and then assigns the result.
Example:
x += 5; // x is now 15 (10 + 5)
x *= 2; // x is now 30 (15 * 2)
2. Arithmetic Operators
These operators are used to perform mathematical calculations.
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulus (remainder after division)**
: Exponentiation (power of)
Example:
let a = 10;
let b = 3;
let sum = a + b; // 13
let diff = a – b; // 7
let product = a * b; // 30
let quotient = a / b; // 3.33
let remainder = a % b; // 1
let power = a ** b; // 1000 (10^3)
3. Comparison Operators
Comparison operators are used to compare two values and return a Boolean value (true
or false
).
==
: Equal to (compares values, but not types).===
: Strict equal to (compares values and types).!=
: Not equal to.!==
: Strict not equal to.>
: Greater than.<
: Less than.>=
: Greater than or equal to.<=
: Less than or equal to.
Example:
let x = 10;
let y = “10”;
con
sole.log(x == y); // true (compares values only)
console.log(x === y); // false (compares both value and type)
console.log(x > 5); // true
console.log(x <= 10); // true
4. Logical Operators
Logical operators are used to combine conditions or invert them.
&&
(AND): Returnstrue
if both conditions are true.||
(OR): Returnstrue
if at least one condition is true.!
(NOT): Inverts the Boolean value (i.e.,true
becomesfalse
and vice versa).
Example:
let x = 5;
let y = 10;
console.log(x > 0 && y > 0); // true (both conditions are true)
console.log(x < 0 || y > 0); // true (one condition is true)
console.log(!(x > 0)); // false (inverts the result)
5. Increment and Decrement Operators
These operators are used to increase or decrease a variable’s value by one.
++
: Increment (increases the value by 1).--
: Decrement (decreases the value by 1).
There are two forms:
- Prefix form (
++x
or--x
): Increments/decrements before using the value. - Postfix form (
x++
orx--
): Increments/decrements after using the value.
Example:
let count = 5;
console.log(++count); // 6 (increments first, then uses the value)
console.log(count++); // 6 (uses the value first, then increments)
console.log(count); // 7 (final value after increment)
6. Ternary (Conditional) Operator
The ternary operator is a shorthand for the if-else
statement. It evaluates a condition and returns one value if true, and another value if false.
Syntax:
Example:
let age = 18;
let isAdult = (age >= 18) ? “Yes” : “No”;
console.log(isAdult); // “Yes”
Example Combining Variables and Operators
// Declare variables
let price = 100;
let discount = 20;
let finalPrice = price – discount; // Using arithmetic operator
// Compare values using comparison operator
if (finalPrice < 100) {
console.log(“You got a discount!”);
} else {
console.log(“No discount applied.”);
}
// Logical operation
let isMember = true;
let canGetDiscount = finalPrice < 100 && isMember;
console.log(“Eligible for further discount: ” + canGetDiscount);
In this example:
- Variables hold the price and discount values.
- Arithmetic operators calculate the final price.
- Comparison and logical operators check eligibility for a discount.
3.3 Understanding the Document Object Model (DOM)
The Document Object Model (DOM) is a programming interface that represents the structure of an HTML or XML document as a tree of objects. It allows developers to manipulate the content, structure, and styles of web pages dynamically with JavaScript.
3.3.1 What is the DOM?
The DOM is essentially a tree-like representation of the HTML document. Each element in the HTML document (like <html>
, <head>
, <body>
, <div>
, etc.) is represented as an object in the DOM. These objects are called nodes.
Here’s an example of how an HTML document is transformed into a DOM tree:
HTML Code:
<html lang=”en”>
<head>
<title>My Web Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>
DOM Tree Representation:
├── <html>
├── <head>
│ └── <title>
└── <body>
├── <h1>
└── <p>
The document starts at the root node (Document
), and each HTML element forms a node connected in a tree-like structure.
3.3.2 Nodes in the DOM
Each part of an HTML document is represented as a node in the DOM. These nodes have relationships with one another:
- Element nodes represent HTML elements.
- Text nodes represent the text content inside elements.
- Attribute nodes represent the attributes on HTML elements.
- Document node represents the entire document (the root node).
Example:
In the following HTML code:
- The
<h1>
element is an element node. - The text
Welcome!
is a text node. - The
class="header"
is an attribute node.
3.3.3 Accessing the DOM with JavaScript
JavaScript can access and manipulate the DOM to dynamically change a web page’s content, structure, and style. JavaScript provides several methods to target DOM elements:
1. Selecting Elements in the DOM
JavaScript allows you to select elements in the DOM using various methods:
document.getElementById(id)
: Selects an element by its ID.document.getElementsByClassName(className)
: Selects all elements with a specified class.document.getElementsByTagName(tagName)
: Selects all elements with a specified tag.document.querySelector(selector)
: Selects the first element that matches a CSS selector.document.querySelectorAll(selector)
: Selects all elements that match a CSS selector.
Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>DOM Manipulation</title>
</head>
<body>
<h1 id=”title”>Welcome to my page!</h1>
<p class=”text”>This is a paragraph.</p>
<script>
// Select element by ID
let title = document.getElementById(‘title’);
console.log(title.textContent); // “Welcome to my page!”
// Select element by class
let paragraph = document.getElementsByClassName(‘text’)[0];
console.log(paragraph.textContent); // “This is a paragraph.”
</script>
</body>
</html>
3.3.4 Modifying the DOM
Once you’ve selected elements, you can modify their content, structure, or style.
1. Changing the Text Content
You can change the text inside an HTML element using the textContent
or innerHTML
properties.
2. Changing the Attributes
You can modify an element’s attributes like src
, href
, class
, etc.
3. Changing the Styles
You can change the inline styles of an element using the style
property.
document.getElementById(‘title’).style.fontSize = “24px”;
4. Adding or Removing Elements
You can add or remove elements from the DOM using the following methods:
createElement()
: Creates a new HTML element.appendChild()
: Adds a new child element to a parent node.removeChild()
: Removes a child element from a parent node.
// Create a new <p> element
let newParagraph = document.createElement(‘p’);
newParagraph.textContent = “This is a new paragraph.”;
// Append it to the body
document.body.appendChild(newParagraph);
// Remove an existing element
let oldParagraph = document.getElementById(‘old-paragraph’);
document.body.removeChild(oldParagraph);
3.3.5 Event Handling in the DOM
The DOM allows JavaScript to respond to events such as clicks, keyboard inputs, or mouse movements. JavaScript can attach event listeners to DOM elements to detect when these events occur.
Common Events:
click
: Triggered when an element is clicked.mouseover
: Triggered when the mouse hovers over an element.keydown
: Triggered when a key is pressed on the keyboard.submit
: Triggered when a form is submitted.
Adding Event Listeners:
document.getElementById(‘myButton’).addEventListener(‘click’, function() {
alert(‘Button was clicked!’);
});
Example with Event Handling:
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Event Handling</title>
</head>
<body>
<h1>Click the button below:</h1>
<button id=”myButton”>Click me!</button>
<script>
// Add click event listener to the button
document.getElementById(‘myButton’).addEventListener(‘click’, function() {
alert(‘You clicked the button!’);
});
</script>
</body>
</html>
In this example, when the button is clicked, an alert will pop up with the message “You clicked the button!”.
3.3.6 Traversing the DOM
The DOM allows you to navigate between nodes, allowing you to traverse up, down, and across the DOM tree.
Common Properties for Traversing:
parentNode
: Selects the parent node of an element.childNodes
: Selects all child nodes (including text nodes).firstChild
,lastChild
: Selects the first or last child node.nextSibling
,previousSibling
: Selects the next or previous sibling of an element.
Example:
let parent = document.getElementById(‘myElement’).parentNode;
console.log(parent); // Logs the parent element
let firstChild = document.body.firstChild;
console.log(firstChild); // Logs the first child of the body element
3.3.7 DOM Tree Structure
The DOM represents the document as a hierarchical tree. Here are the basic types of nodes in the DOM tree:
- Document Node: The root node that represents the entire document.
- Element Nodes: HTML tags, such as
<body>
,<div>
, and<p>
, are element nodes. - Text Nodes: The actual content of HTML elements (text between tags).
- Comment Nodes: HTML comments (
<!-- comment -->
) are also part of the DOM.
3.4 Accessing HTML Elements with getElementById(), getElementsByClassName(), getElementsByName(), getElementsByTagName()
JavaScript provides several methods to access and interact with HTML elements in the DOM (Document Object Model). These methods allow you to target elements by their ID, class, name attribute, or tag name, and then manipulate them.
3.4.1 getElementById()
The getElementById()
method is used to select an HTML element based on its unique id
attribute. Since id
values must be unique within a document, this method will return a single element.
Syntax:
id
: Theid
attribute of the element you want to select.
Example:
<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<h1 id=”header”>Hello, World!</h1>
<p id=”description”>This is a paragraph.</p>
<script>
// Access the element with id=”header”
let header = document.getElementById(‘header’);
console.log(header.textContent); // Outputs: “Hello, World!”
// Modify the text content of the element
header.textContent = “Welcome!”;
</script>
</body>
</html>
In this example:
- The
getElementById('header')
method selects the<h1>
element by itsid
and logs its content. - The
textContent
property is then modified to change the displayed text from “Hello, World!” to “Welcome!”.
3.4.2 getElementsByClassName()
The getElementsByClassName()
method selects all HTML elements that have a specific class name. It returns a live HTMLCollection (an array-like object) containing all matching elements. Since many elements can share the same class, this method usually returns multiple elements.
Syntax:
className
: The name of the class whose elements you want to select.
Example:
<!DOCTYPE html>
<html>
<head>
<title>getElementsByClassName Example</title>
</head>
<body>
<p class=”info”>Paragraph 1</p>
<p class=”info”>Paragraph 2</p>
<p class=”text”>Paragraph 3</p>
<script>
// Access all elements with class=”info”
let paragraphs = document.getElementsByClassName(‘info’);
// Modify the text content of the first element with class=”info”
paragraphs[0].textContent = “Updated Paragraph 1″;
// Log the total number of elements with class=”info”
console.log(paragraphs.length); // Outputs: 2
</script>
</body>
</html>
In this example:
- The
getElementsByClassName('info')
method selects all<p>
elements with the class"info"
. - The first element’s content is updated using
paragraphs[0].textContent
. - The
length
property shows how many elements were selected.
3.4.3 getElementsByName()
The getElementsByName()
method selects all elements that have the specified name
attribute. This method is commonly used to access elements like form fields, which often share the same name
attribute. It returns a NodeList of matching elements.
Syntax:
name
: The value of thename
attribute of the elements you want to select.
Example:
<!DOCTYPE html>
<html>
<head>
<title>getElementsByName Example</title>
</head>
<body>
<form>
<input type=”text” name=”username” value=”John”>
<input type=”password” name=”password”>
<input type=”text” name=”username” value=”Doe”>
</form>
<script>
// Access all input elements with name=”username”
let usernames = document.getElementsByName(‘username’);
// Log the value of each username input
usernames.forEach((input) => {
console.log(input.value); // Outputs: “John”, “Doe”
});
// Modify the value of the first username input
usernames[0].value = “Alice”;
</script>
</body>
</html>
In this example:
- The
getElementsByName('username')
method selects all<input>
elements with thename="username"
. - The
value
property is used to log and modify the content of the input fields.
3.4.4 getElementsByTagName()
The getElementsByTagName()
method selects all elements that match a specified tag name (such as div
, p
, h1
, etc.). This method returns a live HTMLCollection of elements with the given tag name. You can use this method to target groups of similar elements.
Syntax:
tagName
: The name of the tag to select (without angle brackets).
Example:
<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
<script>
// Access all <div> elements
let divs = document.getElementsByTagName(‘div’);
// Log the text content of each div element
for (let i = 0; i < divs.length; i++) {
console.log(divs[i].textContent);
}
// Modify the content of the second <div>
divs[1].textContent = “Updated Second div”;
</script>
</body>
</html>
In this example:
- The
getElementsByTagName('div')
method selects all<div>
elements in the document. - The text content of each
div
is logged in the console, and the seconddiv
is updated with new content.
Key Differences between Methods
Method | Returns | Usage | Example |
---|---|---|---|
getElementById() |
Single element | Selects a single element by id . |
document.getElementById('header') |
getElementsByClassName() |
HTMLCollection | Selects all elements by class name. | document.getElementsByClassName('info') |
getElementsByName() |
NodeList | Selects all elements by name . |
document.getElementsByName('username') |
getElementsByTagName() |
HTMLCollection | Selects all elements by tag name. | document.getElementsByTagName('div') |
3.5 JavaScript objects: window, document, array, string, math, date
In JavaScript, objects are collections of properties and methods. JavaScript provides several built-in objects that help in performing common tasks. In this section, we will discuss some key objects: window
, document
, array
, string
, math
, and date
.
3.5.1 The window
Object
The window
object represents the browser window or frame that contains a web page. It is the global object in a web browser, meaning all global variables and functions are properties of the window
object.
Common Properties and Methods:
window.alert()
: Displays an alert box with a message.window.console.log()
: Outputs messages to the browser’s console.window.innerHeight
/window.innerWidth
: Get the height and width of the browser window.window.setTimeout()
: Executes a function after a specified delay.window.setInterval()
: Repeatedly executes a function at specified intervals.
Example:
// Display an alert box
window.alert(“Welcome to my website!”);
// Log a message to the console
window.console.log(“This message is displayed in the console.”);
// Get the window’s width
let windowWidth = window.innerWidth;
console.log(“Window Width: ” + windowWidth);
In practice, you can omit the window
part, and just use alert()
, console.log()
, etc., as they are globally accessible.
3.5.2 The document
Object
The document
object represents the webpage loaded in the browser. It is part of the DOM (Document Object Model) and allows interaction with HTML content through JavaScript.
Common Properties and Methods:
document.getElementById()
: Selects an element by itsid
.document.getElementsByClassName()
: Selects elements by theirclass
.document.querySelector()
: Selects the first element that matches a CSS selector.document.createElement()
: Creates a new HTML element.document.write()
: Writes content directly to the document (though it’s rarely used today).
Example:
// Select an element by its ID and change its text content
let header = document.getElementById(“header”);
header.textContent = “Welcome to the JavaScript World”;
// Create a new paragraph element and add it to the body
let newParagraph = document.createElement(“p”);
newParagraph.textContent = “This is a new paragraph added via JavaScript.”;
document.body.appendChild(newParagraph);
3.5.3 The array
Object
An array
is a collection of items that are stored at contiguous memory locations. JavaScript arrays are dynamic and can hold values of different types.
Creating an Array:
Common Methods:
push()
: Adds an item to the end of the array.pop()
: Removes the last item from the array.shift()
: Removes the first item from the array.unshift()
: Adds an item to the beginning of the array.length
: Returns the length (number of elements) of the array.sort()
: Sorts the array alphabetically or numerically.forEach()
: Executes a provided function for each array element.
Example:
let fruits = [“Apple”, “Banana”, “Cherry”];
// Add an element to the array
fruits.push(“Orange”); // [“Apple”, “Banana”, “Cherry”, “Orange”]
// Remove the last element
fruits.pop(); // [“Apple”, “Banana”, “Cherry”]
// Loop through each item
fruits.forEach(function(fruit) {
console.log(fruit);
});
3.5.4 The string
Object
The string
object is used to work with text. JavaScript strings are immutable, meaning once a string is created, it cannot be modified directly.
Common Methods:
length
: Returns the length of the string.charAt(index)
: Returns the character at the specified index.toUpperCase()
: Converts the string to uppercase.toLowerCase()
: Converts the string to lowercase.substring(start, end)
: Extracts characters from a string between two indices.split()
: Splits a string into an array based on a separator.replace(oldValue, newValue)
: Replaces a specified value with another.
Example:
let message = “Hello, World!”;
// Get the length of the string
console.log(message.length); // 13
// Convert to uppercase
console.log(message.toUpperCase()); // “HELLO, WORLD!”
// Extract a substring
console.log(message.substring(0, 5)); // “Hello”
// Replace a word
let newMessage = message.replace(“World”, “JavaScript”);
console.log(newMessage); // “Hello, JavaScript!”
3.5.5 The math
Object
The math
object provides mathematical constants and functions. Unlike other objects, you cannot instantiate the math
object because it’s not a constructor.
Common Properties and Methods:
Math.PI
: The value of π (Pi).Math.round(x)
: Rounds a number to the nearest integer.Math.random()
: Returns a random number between 0 (inclusive) and 1 (exclusive).Math.floor(x)
: Rounds a number down to the nearest integer.Math.ceil(x)
: Rounds a number up to the nearest integer.Math.max(x1, x2, ...)
: Returns the largest of the given numbers.Math.min(x1, x2, ...)
: Returns the smallest of the given numbers.
Example:
let number = 4.7;
// Round the number
console.log(Math.round(number)); // 5
// Generate a random number between 0 and 1
console.log(Math.random()); // 0.3467 (example)
// Find the maximum value
console.log(Math.max(10, 20, 30, 40)); // 40
3.5.6 The date
Object
The date
object is used to work with dates and times in JavaScript. It provides methods to retrieve and manipulate dates.
Creating a Date Object:
Common Methods:
getFullYear()
: Returns the four-digit year (e.g., 2024).getMonth()
: Returns the month (0-11). January is0
, and December is11
.getDate()
: Returns the day of the month (1-31).getHours()
: Returns the hour (0-23).getMinutes()
: Returns the minutes (0-59).getTime()
: Returns the number of milliseconds since January 1, 1970.setDate(day)
: Sets the day of the month.
Example:
let today = new Date();
// Get the current year
console.log(today.getFullYear()); // 2024
// Get the current month (0-based index, January = 0)
console.log(today.getMonth() + 1); // 10 (October)
// Get the current day of the month
console.log(today.getDate()); // 7
// Get the current time (hours, minutes)
console.log(today.getHours() + “:” + today.getMinutes()); // e.g., “15:30”
3.6 Writing scripts to handle events
3.6 Writing Scripts to Handle Events in JavaScript
In JavaScript, an event is an action or occurrence that can be detected by the program. Some common events include clicks, key presses, mouse movements, and form submissions. Event handling refers to writing JavaScript code that responds to these events, providing interactivity to web pages.
3.6.1 What Are Events?
An event occurs when a user interacts with an HTML element. Examples of events include:
- Clicking a button
- Submitting a form
- Moving the mouse over an element
- Pressing a key on the keyboard
- Loading a page
JavaScript can be used to “listen” for these events and perform specific actions in response.
3.6.2 Event Listeners
An event listener is a JavaScript function that waits for a specific event to happen and then executes code when the event occurs. There are several ways to assign event listeners in JavaScript.
Adding Event Listeners:
- Inline event handling (within HTML elements)
- Using the
addEventListener()
method (preferred method)
Example Events:
click
: When a user clicks an element.mouseover
: When a user moves the mouse pointer over an element.keydown
: When a key is pressed on the keyboard.submit
: When a form is submitted.load
: When the page finishes loading.
3.6.3 Inline Event Handling (Using HTML Attributes)
You can handle events by adding event attributes directly in HTML elements. Although this is not the preferred method because it mixes HTML and JavaScript, it’s simple to implement.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline Event Handling</title>
</head>
<body>
<button onclick=”sayHello()”>Click Me</button>
<script>
function sayHello() {
alert(“Hello, world!”);
}
</script>
</body>
</html>
In this example:
- The
onclick
attribute is used to define an event handler for the button. When the button is clicked, thesayHello()
function is called, which displays an alert box.
3.6.4 Using the addEventListener()
Method
The preferred way to handle events is to use the addEventListener()
method. This method allows you to separate your JavaScript from the HTML, which is good practice.
Syntax:
event
: The event type (e.g.,'click'
,'mouseover'
).function
: The function to execute when the event occurs.useCapture
(optional): A boolean indicating whether to use event capturing (default isfalse
).
Example:
<!DOCTYPE html>
<html>
<head>
<title>Event Listener Example</title>
</head>
<body>
<button id=”myButton”>Click Me</button>
<script>
// Select the button element
let button = document.getElementById(‘myButton’);
// Add a ‘click’ event listener to the button
button.addEventListener(‘click’, function() {
alert(“Button clicked!”);
});
</script>
</body>
</html>
In this example:
- The
addEventListener()
method is used to attach a'click'
event listener to the button. - When the button is clicked, the anonymous function is executed, and an alert is shown.
3.6.5 Handling Mouse Events
Mouse events are triggered when a user interacts with the mouse. Some common mouse events include:
click
: When the user clicks on an element.dblclick
: When the user double-clicks on an element.mouseover
: When the mouse pointer moves over an element.mouseout
: When the mouse pointer leaves an element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Mouse Events</title>
</head>
<body>
<button id=”hoverButton”>Hover over me</button>
<script>
let button = document.getElementById(‘hoverButton’);
// Add mouseover event listener
button.addEventListener(‘mouseover’, function() {
button.textContent = “Mouse is over me!”;
});
// Add mouseout event listener
button.addEventListener(‘mouseout’, function() {
button.textContent = “Hover over me”;
});
</script>
</body>
</html>
In this example:
- The button text changes when the mouse hovers over it (
mouseover
event) and reverts when the mouse moves away (mouseout
event).
3.6.6 Handling Keyboard Events
Keyboard events are triggered when the user presses keys on the keyboard. Common keyboard events include:
keydown
: When the user presses a key.keyup
: When the user releases a key.
Example:
<!DOCTYPE html>
<htSubjectsml>
<head>
<title>Keyboard Events</title>
</head>
<body>
<input type=”text” id=”textInput” placeholder=”Type something…”>
<script>
let input = document.getElementById(‘textInput’);
// Add a keydown event listener
input.addEventListener(‘keydown’, function(event) {
console.log(“Key pressed: ” + event.key);
});
</script>
</body>
</html>
In this example:
- When the user presses any key while typing in the input field, the
keydown
event is triggered, and the key pressed is logged to the console.
3.6.7 Handling Form Events
Forms often require event handling to manage actions such as submitting or validating user input. Some form-related events include:
submit
: Triggered when the form is submitted.focus
: Triggered when an element (e.g., input field) gains focus.blur
: Triggered when an element loses focus.
Example (Form Submission):
<!DOCTYPE html>
<html>
<head>
<title>Form Event</title>
</head>
<body>
<form id=”myForm”>
<input type=”text” id=”name” placeholder=”Enter your name”>
<input type=”submit” value=”Submit”>
</form>
<script>
let form = document.getElementById(‘myForm’);
// Add a submit event listener to the form
form.addEventListener(‘submit’, function(event) {
event.preventDefault(); // Prevent the default form submission
let nameInput = document.getElementById(‘name’).value;
alert(“Form submitted! Name: ” + nameInput);
});
</script>
</body>
</html>
In this example:
- When the form is submitted, the
submit
event is triggered. - The
event.preventDefault()
method is used to prevent the default form submission behavior, allowing JavaScript to handle the form submission.
3.6.8 Common Event Properties
When handling events, certain event properties are often useful:
event.type
: The type of event that was triggered (e.g.,'click'
,'keydown'
).event.target
: The element that triggered the event.event.preventDefault()
: Prevents the default action associated with the event.event.stopPropagation()
: Stops the event from bubbling up to parent elements.
Example (Using event.target
):
console.log(“Clicked element: ” + event.target.tagName);
});
In this example:
- The
click
event listener logs the tag name of the element that was clicked usingevent.target.tagName
.
3.7 Using JavaScript to Validate User Inputs
Form validation ensures that the user provides the correct input before submitting a form. JavaScript is commonly used for client-side validation to provide real-time feedback without sending data to the server, improving the user experience.
3.7.1 Why Validate User Input?
Validating user input helps to:
- Ensure data is in the expected format.
- Prevent errors from being submitted to the server.
- Protect the server from malicious data or attacks (though server-side validation is also essential for security).
3.7.2 Types of Validation
- Required Field Validation: Ensures that the user has not left a required field empty.
- Data Type Validation: Ensures that the correct data type (e.g., email, number) is provided.
- Length Validation: Ensures that the input length meets certain criteria (e.g., password length).
- Range Validation: Ensures that numerical input falls within a specified range.
- Pattern Matching Validation: Ensures that input matches a specific pattern (e.g., email format).
3.7.3 Using JavaScript for Form Validation
You can use JavaScript to check the form inputs before they are submitted. This is often done by attaching event listeners to the form’s submit
event or by adding oninput
or onchange
event listeners to specific fields.
Example: Basic Form Validation
<!DOCTYPE html>
<html>
<head>
<title>Form Validation Example</title>
</head>
<body>
<h2>Registration Form</h2>
<form id=”registrationForm”>
<label for=”name”>Name:</label>
<input type=”text” id=”name” name=”name”><br><br>
<label for=”email”>Email:</label>
<input type=”email” id=”email” name=”email”><br><br>
<label for=”password”>Password:</label>
<input type=”password” id=”password” name=”password”><br><br>
<input type=”submit” value=”Submit”>
</form>
<script>
// Select the form element
const form = document.getElementById(‘registrationForm’);
// Add a submit event listener
form.addEventListener(‘submit’, function(event) {
// Prevent the default form submission
event.preventDefault();
// Perform validation
const name = document.getElementById(‘name’).value;
const email = document.getElementById(’email’).value;
const password = document.getElementById(‘password’).value;
if (name === ”) {
alert(‘Name is required.’);
return;
}
if (email === ” || !validateEmail(email)) {
alert(‘Please enter a valid email address.’);
return;
}
if (password.length < 6) {
alert(‘Password must be at least 6 characters long.’);
return;
}
alert(‘Form submitted successfully!’);
});
// Helper function to validate email format using regex
function validateEmail(email) {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
</script>
</body>
</html>
Explanation:
- Prevent Form Submission: The
event.preventDefault()
method stops the form from submitting, allowing you to check for valid input first. - Validation Logic: Checks if:
- Name is provided.
- Email is in a valid format (using a regular expression).
- Password is at least 6 characters long.
- Helper Function: The
validateEmail()
function uses a regular expression to check the email format.
3.7.4 Validating Different Input Types
1. Text Input Validation
You can check if a text input is empty or if it meets specific length requirements.
const name = document.getElementById(‘name’).value;
if (name === ”) {
alert(‘Name is required.’);
} else if (name.length < 3) {
alert(‘Name must be at least 3 characters long.’);
}
2. Email Validation
Emails should follow the standard format (example@domain.com
), and you can use a regular expression (regex) to verify this.
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailPattern.test(email);
}
3. Password Validation
Passwords should meet length and complexity requirements.
const password = document.getElementById(‘password’).value;
if (password.length < 6) {
alert(‘Password must be at least 6 characters long.’);
}
4. Radio Button Validation
Ensure that a radio button option is selected.
if (!gender) {
alert(‘Please select a gender.’);
}
5. Checkbox Validation
Ensure at least one checkbox is selected.
if (!terms) {
alert(‘You must agree to the terms and conditions.’);
}
6. Select Option Validation
Ensure an option is selected from a dropdown.
if (country === ”) {
alert(‘Please select your country.’);
}
3.7.5 Real-Time Validation
Real-time validation provides instant feedback to the user as they type. You can use the oninput
or onchange
event to validate inputs as the user enters data.
Example (Real-Time Validation):
<!DOCTYPE html>
<html>
<head>
<title>Real-Time Validation</title>
</head>
<body>
<label for=”username”>Username:</label>
<input type=”text” id=”username” name=”username” oninput=”validateUsername()”>
<span id=”usernameError” style=”color: red;”></span>
<script>
function validateUsername() {
const username = document.getElementById(‘username’).value;
const errorSpan = document.getElementById(‘usernameError’);
if (username.length < 3) {
errorSpan.textContent = ‘Username must be at least 3 characters long.’;
} else {
errorSpan.textContent = ”;
}
}
</script>
</body>
</html>
In this example:
- The
validateUsername()
function is called every time the user types in the input field. - If the username is too short, an error message is displayed in real-time.
3.7.6 Custom Validation Messages
You can provide custom validation messages for a better user experience. The setCustomValidity()
method allows you to set a custom message for invalid inputs.
Example (Custom Message):
<input type=”text” id=”username” name=”username” oninput=”validateInput(this)”>
<span id=”error”></span>
<script>
function validateInput(input) {
if (input.value.length < 3) {
input.setCustomValidity(‘Username must be at least 3 characters long.’);
} else {
input.setCustomValidity(”); // Clears the error message
}
}
</script>
3.7.7 HTML5 Form Validation Features
HTML5 introduces built-in form validation features, such as:
required
: Specifies that the input must be filled out before submitting.minlength
andmaxlength
: Specifies the minimum and maximum number of characters.pattern
: Specifies a regular expression pattern the input must match.type="email"
,type="number"
: Specifies the type of data the input expects, like an email or number.
These attributes work out of the box, but JavaScript validation is still useful for more complex rules and custom error messages.