Client-Side Scripting
Client-side scripting involves scripts that run in the user's browser, enhancing interactivity and
functionality without needing constant server interaction. JavaScript is the most widely used language
for this purpose.
JavaScript Programming Constructs
1. Control Structures: Control structures manage the flow of the program.
Conditional Statements:
if, else if, else
Example
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
Switch Statement:
javascript
Copy code
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
Loops:
for, while, do-while
Example
for (let i = 0; i < 5; i++) {
console.log(i);
Functions: Encapsulates reusable blocks of code.
Declaration
function greet(name) {
return `Hello, ${name}`;
console.log(greet("Alice"));
Anonymous Functions (Used with event handlers or as callbacks
let add = function (a, b) {
return a + b;
};
console.log(add(5, 3));
Arrow Functions
let multiply = (x, y) => x * y;
console.log(multiply(4, 2));
Arrays: Used to store multiple values.
Example:
Methods:
push(), pop(), shift(), unshift()
map(), filter(), reduce()
example
fruits.push("Dragonfruit");
console.log(fruits); // ["Apple", "Banana", "Cherry", "Dragonfruit"]
Objects: Collections of key-value pairs
let person = {
name: "John",
age: 30,
greet: function() {
return `Hi, I am ${this.name}`;
};
console.log(person.greet());
Forms: JavaScript interacts with HTML forms for validation and data processing.
Accessing Form Elements:
javascript
Copy code
let form = document.getElementById("myForm");
form.onsubmit = function (event) {
event.preventDefault(); // Prevents form submission
let name = document.getElementById("name").value;
console.log(name);
};
Object-Based Programming: JavaScript uses prototypes instead of traditional classes (ES5), but ES6
introduced the class keyword
class Car {
constructor(brand, year) {
this.brand = brand;
this.year = year;
display() {
return `${this.brand} was made in ${this.year}`;
let myCar = new Car("Toyota", 2020);
console.log(myCar.display());
Event Handlers: JavaScript responds to user interactions through events
Inline
<button onclick="alert('Button clicked!')">Click Me</button>
Adding Event Listeners:
let btn = document.getElementById("myButton");
btn.addEventListener("click", () => {
alert("Button was clicked!");
});
JavaScript Object Library
The JavaScript object library refers to built-in objects provided by JavaScript that help in various
operations. These objects enhance the functionality of JavaScript and include:
1. Core JavaScript Objects
1. Global Objects:
Object, Function, Array, String, Number, Boolean, Date, RegExp, Map, Set, WeakMap, W
eakSet, etc.
let str = new String("Hello"); // String Object
let date = new Date(); // Date Object
let numbers = [1, 2, 3]; // Array Object
Math Object: Provides mathematical constants and functions.
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
console.log(Math.random()); // Random number between 0 and 1
Date Object: Used for date and time manipulation.
let now = new Date();
console.log(now.toISOString()); // Current date in ISO format
JSON (JavaScript Object Notation): Used for parsing and stringifying JSON data.
let jsonData = '{"name": "Alice", "age": 25}';
let obj = JSON.parse(jsonData); // Convert JSON to object
console.log(obj.name); // Alice
RegExp (Regular Expressions): Used for pattern matching in strings.
let regex = /hello/i;
console.log(regex.test("Hello")); // true
2. Custom Objects
You can define your own objects using:
Object Literals:
let car = {
brand: "Toyota",
year: 2020,
drive: function() {
console.log("Driving...");
};
car.drive();
Constructor Functions:
function Person(name, age) {
this.name = name;
this.age = age;
let p = new Person("John", 30);
console.log(p.name); // John
Classes (ES6):
class Animal {
constructor(name) {
this.name = name;
speak() {
console.log(`${this.name} makes a noise.`);
let dog = new Animal("Dog");
dog.speak();
Document Object Model (DOM)
The DOM represents the structure of an HTML or XML document as a tree of objects. Using JavaScript,
we can interact with and manipulate this structure.
1. Accessing DOM Elements
1. Using Selectors:
let elemById = document.getElementById("myId"); // Select by ID
let elemsByClass = document.getElementsByClassName("myClass"); // Select by class
let elemsByTag = document.getElementsByTagName("div"); // Select by tag name
let query = document.querySelector(".myClass"); // Select first matching element
let allQuery = document.querySelectorAll("div.myClass"); // Select all matching elements
Example:
<div id="myId">Hello World</div>
<script>
let element = document.getElementById("myId");
console.log(element.textContent); // "Hello World"
</script>
2. Modifying DOM Elements
1. Changing Content:
let para = document.getElementById("para");
para.textContent = "New content";
para.innerHTML = "<strong>Bold content</strong>";
Changing Attributes:
let img = document.querySelector("img");
img.setAttribute("src", "new_image.png");
img.alt = "New description";
Styling Elements:
let div = document.getElementById("box");
div.style.backgroundColor = "blue";
div.style.width = "100px";
Creating and Inserting Elements
1. Create and Append:
let newDiv = document.createElement("div");
newDiv.textContent = "I am new!";
document.body.appendChild(newDiv);
Insert Before:
let parent = document.getElementById("container");
let child = document.getElementById("child");
let newChild = document.createElement("div");
newChild.textContent = "Inserted!";
parent.insertBefore(newChild, child);
Removing Elements
let elem = document.getElementById("myElement");
elem.remove(); // Removes the element
5. Event Listeners and Handlers
JavaScript can interact with the DOM via events.
Adding Events:
let button = document.getElementById("btn");
button.addEventListener("click", () => {
alert("Button clicked!");
});
Removing Events:
let handler = () => alert("Clicked!");
button.addEventListener("click", handler);
button.removeEventListener("click", handler);
Summary
JavaScript Object Library provides built-in objects for manipulating data, performing
computations, and working with JSON, regular expressions, dates, and more.
DOM is the interface through which JavaScript interacts with the structure of a webpage,
allowing you to modify, create, and remove elements dynamically, and respond to user events.
Working with Arrays or Objects: Exercises on array methods
like map, filter, or object manipulation.
DOM Manipulation: Examples of adding dynamic elements to a
webpage, modifying styles, or creating interactive content.
Event Handling: Exercises on handling button clicks, form
submissions, or keypress events.
Form Validation: Practical examples of client-side form validation
using JavaScript.
Object-Oriented Programming: Challenges involving custom
objects, classes, and inheritance.
Forms, Links, Anchors, Image Maps, and Cookies in JavaScript
Here’s a comprehensive overview of these topics with examples:
1. Forms
Forms are used for collecting user inputs, and JavaScript allows you to manipulate forms dynamically for
validation and interaction.
Accessing Form Elements
Get form and input value
<form id="myForm">
<input type="text" id="name" placeholder="Enter name" />
<input type="submit" value="Submit" />
</form>
<script>
let form = document.getElementById("myForm");
form.onsubmit = (event) => {
event.preventDefault(); // Prevent actual form submission
let name = document.getElementById("name").value;
alert(`Hello, ${name}!`);
};
</script>
Validating Form Inputs
let input = document.getElementById("name");
if (input.value === "") {
alert("Name cannot be empty!");
Form Reset and Autofocus
form.reset();
Autofocus on a field:
<input type="text" autofocus />
2. Links
JavaScript can manipulate or create hyperlinks dynamically.
Example: Add a link dynamically
<div id="links"></div>
<script>
let link = document.createElement("a");
link.href = "https://www.google.com";
link.textContent = "Go to Google";
document.getElementById("links").appendChild(link);
</script>
Prevent Default Behavior of a Link
<a href="https://www.example.com" id="myLink">Click me</a>
<script>
let link = document.getElementById("myLink");
link.addEventListener("click", (event) => {
event.preventDefault(); // Prevents navigation
alert("Link clicked, but navigation prevented!");
});
</script>
3. Anchors
Anchors allow navigation within the same page using the id attribute of an element.
Example: Scroll to a specific section
html
Copy code
<a href="#section2">Go to Section 2</a>
<div style="height: 500px;"></div>
<h2 id="section2">Section 2</h2>
4. Image Maps
Image maps allow specific areas of an image to act as links.
Example: Interactive Image Map
<img src="example.jpg" usemap="#imagemap" alt="Sample Image" />
<map name="imagemap">
<area shape="rect" coords="34,44,270,350" href="https://example.com" alt="Example">
<area shape="circle" coords="337,300,44" href="https://anotherexample.com" alt="Another
Example">
</map>
Shapes in <area>:
rect: Rectangle (x1, y1, x2, y2)
circle: Circle (x, y, radius)
poly: Polygon (x1, y1, x2, y2, ... xn, yn)
5. Cookies
Cookies are small pieces of data stored in the browser to remember information.
Set a Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 12:00:00 UTC; path=/";
Get Cookies
console.log(document.cookie); // Outputs all cookies
Delete a Cookie
To delete a cookie, set its expires attribute to a past date.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
Example: Read and Write Cookies
<script>
// Set a cookie
document.cookie = "theme=dark; path=/";
// Retrieve cookies
let cookies = document.cookie.split("; ");
cookies.forEach(cookie => {
let [key, value] = cookie.split("=");
console.log(`${key}: ${value}`);
});
</script>
Combining Features: Example Form with Cookies
<form id="loginForm">
<input type="text" id="username" placeholder="Enter Username" />
<input type="password" id="password" placeholder="Enter Password" />
<button type="submit">Login</button>
</form>
<script>
let form = document.getElementById("loginForm");
form.onsubmit = (event) => {
event.preventDefault();
let username = document.getElementById("username").value;
// Save the username in a cookie
document.cookie = `username=${username}; path=/`;
alert(`Welcome, ${username}!`);
};
// Display stored username from cookie
let cookies = document.cookie.split("; ");
cookies.forEach(cookie => {
let [key, value] = cookie.split("=");
if (key === "username") {
alert(`Welcome back, ${value}!`);
}
});
</script>
Summary
Forms: Used for input collection and validation.
Links and Anchors: Provide navigation within or between pages.
Image Maps: Enable interactive image-based navigation.
Cookies: Store small pieces of data in the browser for state management.
Great! If you'd like, I can provide:
1. Exercises:
Forms: Validating multiple fields (e.g., email, password), creating interactive forms.
Links/Anchors: Dynamically generating navigation menus or handling internal page
scrolling.
Image Maps: Design a clickable image map for a city map or a website layout.
Cookies: Build a "Remember Me" feature or a theme selector that persists across visits.
2. Deeper Examples:
Advanced Form Handling: Integrating JavaScript with APIs (e.g., login systems).
Dynamic Anchors and Links: Generating navigation menus from JSON data.
Interactive Image Maps: Highlight areas on hover and display information in a tooltip.
Cookies with Storage APIs: Comparing cookies, localStorage, and sessionStorage for
data persistence.