0% found this document useful (0 votes)
2 views36 pages

JS

This document covers the fundamentals of client-side scripting using JavaScript, including its key features, common languages, and examples of usage. It distinguishes between client-side and server-side scripting, explains variable declaration, data types, operators, functions, control flow statements, and array manipulation. Additionally, it provides examples and explanations for various JavaScript concepts to enhance understanding of web technology and UI/UX design.

Uploaded by

hetraj189
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

JS

This document covers the fundamentals of client-side scripting using JavaScript, including its key features, common languages, and examples of usage. It distinguishes between client-side and server-side scripting, explains variable declaration, data types, operators, functions, control flow statements, and array manipulation. Additionally, it provides examples and explanations for various JavaScript concepts to enhance understanding of web technology and UI/UX design.

Uploaded by

hetraj189
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Course Code: 1010043228

Course Name: Web Technology with


UIUX

SEMESTER: 4

Unit 3
Working With JavaScript

Client Side Scripting


●​ Client-side scripting refers to code that is executed in the user's web browser rather than on a web server.
●​ It is mainly used to create interactive and dynamic web pages.
●​ Client-side scripts are typically written in languages like JavaScript, HTML, and CSS.

Key Features of Client-Side Scripting:

●​ Runs in the user's browser (e.g., Chrome, Firefox, Edge).


●​ Reduces server load by handling tasks on the client-side.
●​ Enhances user experience with interactive elements.
●​ Can manipulate the Document Object Model (DOM) for real-time updates.
●​ Cannot access server-side databases directly (for security reasons).

Common Client-Side Scripting Languages:

1.​ JavaScript – The primary language for client-side interactivity.


2.​ HTML & CSS – Used for structuring and styling web pages.
3.​ TypeScript – A superset of JavaScript, often compiled to JavaScript.
4.​ WebAssembly (WASM) – Allows running high-performance code (e.g., C, C++).

Examples of Client-Side Scripting:

●​ Form validation (checking if fields are filled before submission).


●​ Animations and transitions using CSS and JavaScript.
●​ Fetching and displaying real-time data using AJAX.
●​ Interactive elements like drop-down menus, sliders, and pop-ups.
Difference Between Client Side Scripting and Server Side Scripting

Feature Client-Side Scripting Server-Side Scripting

Execution Location Runs in the user's web browser Runs on the web server

Languages Used JavaScript, HTML, CSS PHP, Python, Node.js, ASP.NET,


Ruby, Java, etc.

Purpose Enhances user interaction, UI Handles business logic, database


updates, and validation operations, and server-side
computations

Speed Faster since it runs locally on the Slower due to communication with
user's device the server

Security Less secure, as the code is visible More secure, as code runs on the
to the user server and is hidden from the user

Dependency on Can work offline for static Requires an internet connection for
Internet content processing

Examples Form validation, animations, User authentication, data storage,


interactive UI elements dynamic content generation
Variables

Variables in JavaScript are used to store data values. They can hold different types of data such as
numbers, strings, objects, etc.

Declaring Variables

JavaScript provides three keywords to declare variables:

1.​ var – Global or function-scoped (older method)


2.​ let – Block-scoped (introduced in ES6)
3.​ const – Block-scoped, cannot be reassigned (constant)

Examples

var x = 10; // Function-scoped variable


let y = 20; // Block-scoped variable
const z = 30; // Block-scoped constant (cannot be reassigned)

Key Differences

Feature var let const

Scope Function-scoped Block-scoped Block-scoped

Re-declaration Allowed Not allowed Not allowed

Re-assignment Allowed Allowed Not allowed

Hoisting Yes (initialized as undefineYes (but not initialized) Yes (but not initialized)
Data Type in JavaScript

JavaScript has two main categories of data types: Primitive and Non-Primitive (Reference).

1. Primitive Data Types


Primitive data types are immutable (cannot be changed) and are stored directly in memory.

Data Type Description Example

String Represents textual data "Hello" or 'JavaScript'

Number Represents numeric values (integers and 10, 3.14, -5


floats)

Boolean Represents logical values true, false


Undefined A variable that has been declared but not let x; (x is undefined)
assigned a value

Null Represents an empty or unknown value let y = null;

BigInt Used for very large numbers beyond BigInt(9007199254740991) or


Number.MAX_SAFE_INTEGER 9007199254740991n

Symbol Used to create unique and immutable values let sym = Symbol('id');

2. Non-Primitive (Reference) Data Types


Non-primitive data types are mutable (changeable) and stored as references in memory.

Data Type Description Example

Object Collection of key-value pairs let obj = { name: "John", age: 25

Array Ordered collection of values let arr = [1, 2, 3, "hello"];

Function A reusable block of code function greet() { console.log("Hi


}

Example Code
let name = "Alice"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let score; // Undefined
let emptyValue = null; // Null
let largeNumber = 12345678901234567890n; // BigInt
let uniqueId = Symbol('id'); // Symbol
let person = { name: "Alice", age: 25 }; // Object
let numbers = [1, 2, 3, 4]; // Array
function sayHello() { console.log("Hello"); } // Function

Operators in JavaScript

1. Arithmetic Operators
Used for mathematical calculations.

Operator Description Example Result

+ Addition 5 + 3 8

- Subtraction 5 - 3 2

* Multiplication 5 * 3 15

/ Division 10 / 2 5

% Modulus (Remainder) 10 % 3 1

** Exponentiation (Power) 2 ** 3 8

++ Increment let x = 5; x++ 6

-- Decrement let x = 5; x-- 4

2. Assignment Operators
Used to assign values to variables.

Operator Description Example Equivalent To

= Assign value x = 10 x = 10

+= Add and assign x += 5 x = x + 5


-= Subtract and assign x -= 5 x = x - 5

*= Multiply and assign x *= 5 x = x * 5

/= Divide and assign x /= 5 x = x / 5

%= Modulus and assign x %= 5 x = x % 5

**= Exponentiation and assign x **= 2 x = x ** 2

3. Comparison Operators
Used to compare values and return true or false.

Operator Description Example Result

== Equal to (value) 5 == "5" true

=== Strict equal (value & type) 5 === "5" false

!= Not equal (value) 5 != "5" false

!== Strict not equal (value & type) 5 !== "5" true

> Greater than 10 > 5 true

< Less than 10 < 5 false

>= Greater than or equal to 10 >= 10 true

<= Less than or equal to 10 <= 5 false

4. Logical Operators
Used for boolean logic.
Operator Description Example Result

&& AND true && false false

` ` OR

! NOT !true false

5. Bitwise Operators
Used to perform operations on binary numbers.

Operator Description Example (5 = 0101, 3 = 0011) Result (Binary) Result (Decimal)

& AND 5 & 3 0001 1

` ` OR `5 3`

^ XOR 5 ^ 3 0110 6

~ NOT ~5 1010 -6

<< Left shift 5 << 1 1010 10

>> Right shift 5 >> 1 0010 2

6. Ternary Operator (? :)
A shorthand for if...else.

Example:
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";
console.log(canVote); // Output: Yes
Function

A function in JavaScript is a reusable block of code that performs a specific task. Functions help in
modularizing code, making it more readable and maintainable.

1. Declaring a Function
Function Declaration

A function is declared using the function keyword and can be called before its definition due to
hoisting.

Example:
function greet() {
console.log("Hello, World!");
}
greet(); // Output: Hello, World!

Function Expression (Anonymous Function)

A function can be assigned to a variable. It is not hoisted.

Example:

const greet = function() {


console.log("Hello, World!");
};
greet(); // Output: Hello, World!

Arrow Function (ES6)

A concise way to write functions using =>.

Example:
const greet = () => console.log("Hello, World!");
greet(); // Output: Hello, World!
2. Function Parameters and Return Values
Functions can take parameters and return values.

Example:

function add(a, b) {
return a + b;
}
let sum = add(5, 10);
console.log(sum); // Output: 15

Arrow Function Version:

Example:
const add = (a, b) => a + b;
console.log(add(5, 10)); // Output: 15

3. Default Parameters
If a parameter is not provided, a default value can be used.

Example:
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // Output: Hello, Guest
greet("Alice"); // Output: Hello, Alice

Control flow statements

1. Conditional Statements

These statements execute different blocks of code based on conditions.


if Statement

Executes a block of code if a condition is true.


Example:
let num = 10;
if (num > 5) {
console.log("Number is greater than 5");
}

if-else Statement

Executes one block if the condition is true, otherwise executes another.


Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

if-else if-else Statement

Checks multiple conditions in sequence.


Example:
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 75) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
Switch Statement

A better alternative to multiple if-else statements when checking the same variable against different values.
Example:
l8.

2. Looping Statements

Loops execute a block of code multiple times.

for Loop

Executes a block of code a specific number of times.


Example:
for (let i = 1; i <= 5; i++) {
console.log("Iteration:", i);
}

while Loop

Executes as long as the condition is true.


Example:
let count = 0;
while (count < 3) {
console.log("Count:", count);
count++;
}

do-while Loop

Executes at least once before checking the condition.


Example:
let i = 0;
do {
console.log("Executed at least once");
i++;
} while (i < 1);

3. Branching Statements

Control the flow of loops and functions.

break Statement

Exits a loop or switch statement immediately.


Example:
for (let i = 0; i < 5; i++) {
if (i === 3) break;
console.log(i); // Outputs: 0, 1, 2
}

continue Statement

Skips the current iteration and moves to the next.


Example:
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i); // Outputs: 0, 1, 3, 4
}

return Statement

Exits a function and optionally returns a value.


Example:
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Output: Hello, Alice

Array
An array in JavaScript is a special variable that can store multiple values in a single variable.

Creating an Array
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // ["Apple", "Banana", "Cherry"]
OR using the new Array() constructor:
let numbers = new Array(1, 2, 3, 4, 5);
console.log(numbers); // [1, 2, 3, 4, 5]

Accessing Elements
Example:
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"

Modifying Elements
Example:
fruits[1] = "Mango";
console.log(fruits); // ["Apple", "Mango", "Cherry"]

Array Methods in JavaScript

JavaScript provides various built-in methods to manipulate arrays.

1. Adding & Removing Elements

Method Description

push() Adds an element to the end

pop() Removes the last element


unshift() Adds an element to the beginning

shift() Removes the first element

Examples:
let arr = [1, 2, 3];

arr.push(4);
console.log(arr); // [1, 2, 3, 4]

arr.pop();
console.log(arr); // [1, 2, 3]

arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]

arr.shift();
console.log(arr); // [1, 2, 3]

2. Iterating Over an Array

Method Description

forEach() Calls a function for each element

map() Returns a new array after transformation

filter() Returns a new array with elements that match a conditio

reduce() Reduces the array to a single value

Examples:
let nums = [1, 2, 3, 4, 5];

// forEach()
nums.forEach(num => console.log(num * 2)); // 2, 4, 6, 8, 10
// map()
let squares = nums.map(num => num * num);
console.log(squares); // [1, 4, 9, 16, 25]

// filter()
let evenNums = nums.filter(num => num % 2 === 0);
console.log(evenNums); // [2, 4]

// reduce()
let sum = nums.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

3. Searching & Checking Elements

Method Description

indexOf() Returns index of the first occurrence

lastIndexOf() Returns index of the last occurrence

includes() Checks if an array contains a value

find() Returns the first element that matches a condition

findIndex() Returns the index of the first matching element

Examples:
let arr2 = [10, 20, 30, 40, 50];

console.log(arr2.indexOf(30)); // 2
console.log(arr2.includes(20)); // true
console.log(arr2.find(num => num > 25)); // 30
console.log(arr2.findIndex(num => num > 25)); // 2
4. Modifying & Combining Arrays

Method Description

slice() Returns a portion of an array

splice() Adds or removes elements

concat() Merges arrays

join() Converts an array to a string

Examples:
let animals = ["Dog", "Cat", "Elephant", "Lion"];

// slice()
let someAnimals = animals.slice(1, 3);
console.log(someAnimals); // ["Cat", "Elephant"]

// splice()
animals.splice(2, 1, "Tiger"); // Removes 1 element at index 2, adds
"Tiger"
console.log(animals); // ["Dog", "Cat", "Tiger", "Lion"]

// concat()
let moreAnimals = animals.concat(["Monkey", "Giraffe"]);
console.log(moreAnimals); // ["Dog", "Cat", "Tiger", "Lion", "Monkey",
"Giraffe"]

// join()
console.log(animals.join(" - ")); // "Dog - Cat - Tiger - Lion"
5. Sorting & Reversing Arrays

Method Description

sort() Sorts an array alphabetically

reverse() Reverses the order of elements

Examples:
let numbersArr = [5, 2, 8, 1, 4];

numbersArr.sort();
console.log(numbersArr); // [1, 2, 4, 5, 8]

numbersArr.reverse();
console.log(numbersArr); // [8, 5, 4, 2, 1]

// Sorting numbers correctly


numbersArr.sort((a, b) => a - b);
console.log(numbersArr); // [1, 2, 4, 5, 8]

built-in objects in JavaScript


JavaScript provides several built-in objects that offer useful methods and properties for working with different
data types.
JavaScript comes with some inbuilt objects which are,
String, Date, Array, Boolean, Math, RegExp, etc….
1. Math Object
The Math object provides mathematical functions and constants.

Common Methods
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(25)); // 5
console.log(Math.pow(2, 3)); // 8 (2^3)
console.log(Math.round(4.6)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.random()); // Random number between 0 and 1
console.log(Math.max(10, 5, 20)); // 20
console.log(Math.min(10, 5, 20)); // 5

2. Date Object

The Date object is used to work with dates and times.

Creating a Date
let now = new Date();
console.log(now); // Current date & time

let specificDate = new Date("2023-12-25");


console.log(specificDate); // Christmas 2023

Getting Date Components


console.log(now.getFullYear()); // Current year
console.log(now.getMonth()); // Month (0-based, 0 = January)
console.log(now.getDate()); // Day of the month
console.log(now.getDay()); // Day of the week (0 = Sunday)
console.log(now.getHours()); // Current hour
console.log(now.getMinutes()); // Current minutes
console.log(now.getSeconds()); // Current seconds

Modifying Date
now.setFullYear(2025);
console.log(now.getFullYear()); // 2025
User Define Objects
In JavaScript, you can create user-defined objects to model real-world entities by defining
custom properties and methods.

1. Creating Objects Using Object Literals

The simplest way to create an object is using object literals.

let person = {
name: "Alice",
age: 25,
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};

console.log(person.name); // Alice
person.greet(); // Hello, my name is Alice

2. Creating Objects Using the new Object() Constructor

Another way to create an object is using the Object constructor.

let car = new Object();


car.brand = "Toyota";
car.model = "Camry";
car.year = 2023;
car.displayInfo = function() {
console.log(`${this.brand} ${this.model}, Year: ${this.year}`);
};

car.displayInfo(); // Toyota Camry, Year: 2023


Document Object Model(DOM)
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It
represents the structure of a webpage as a tree of objects, where each HTML element is a node that
can be accessed and manipulated using JavaScript.

🔹 The DOM allows JavaScript to:​


✔️ Access elements (e.g., <div>, <button>)​
✔️ Modify content (e.g., change text, add/remove elements)​
✔️ Change styles (e.g., background color, font size)​
✔️ Handle events (e.g., button clicks, form submissions)

1. DOM Tree Structure


A webpage is represented as a hierarchical tree:

Document
├── <html>
│ ├── <head>
│ │ ├── <title>
│ │ ├── <meta>
│ ├── <body>
│ ├── <h1>
│ ├── <p>
│ ├── <div>
│ ├── <button>

●​ The document object represents the entire HTML page.


●​ Elements like <body>, <h1>, and <button> are nodes in the tree.
2. Selecting Elements in the DOM

Method 1: getElementById() (Selects a single element by its id)


let heading = document.getElementById("main-heading");
console.log(heading.textContent);

Method 2: getElementsByClassName() (Selects multiple elements by class name)


let items = document.getElementsByClassName("list-item");
console.log(items[0].textContent); // Access first item

Method 3: getElementsByTagName() (Selects elements by tag name)


let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs[0].textContent);

Method 4: querySelector() (Selects the first matching element)


let firstItem = document.querySelector(".list-item");
console.log(firstItem.textContent);

Method 5: querySelectorAll() (Selects all matching elements)


let allItems = document.querySelectorAll(".list-item");
allItems.forEach(item => console.log(item.textContent));

3. Modifying Elements in the DOM


Change Text Content
document.getElementById("main-heading").textContent = "Hello, World!";
Change HTML Content
document.getElementById("main-heading").innerHTML = "<span>New
Heading</span>";

Change CSS Styles


document.getElementById("main-heading").style.color = "red";
document.getElementById("main-heading").style.fontSize = "24px";

4. Adding & Removing Elements


Create and Append an Element
let newDiv = document.createElement("div");
newDiv.textContent = "I am a new div!";
document.body.appendChild(newDiv);

Remove an Element
let element = document.getElementById("main-heading");
element.remove();

Events in JavaScript
●​ In JavaScript, events are actions that occur when users interact with a webpage.
●​ These interactions can be clicking a button, typing in an input field, moving the mouse, or loading the page.
JavaScript allows us to handle these events using event listeners.

Types of Events in JavaScript


Event Type Description

click Fires when an element is clicked


dblclick Fires when an element is double-clicked

mouseover Fires when the mouse moves over an element

mouseout Fires when the mouse leaves an element

mousemove Fires when the mouse moves inside an element

keydown Fires when a key is pressed

keyup Fires when a key is released

change Fires when the value of an input field changes

input Fires when the user types in an input field

submit Fires when a form is submitted

focus Fires when an input field gains focus

blur Fires when an input field loses focus

load Fires when the page or an image is fully loaded

scroll Fires when the user scrolls the page

resize Fires when the browser window is resized


Event Handlers in JavaScript
An event handler is a function that is executed when a specific event occurs, such as a button click,
mouse hover, or key press. JavaScript provides several ways to define and manage event handlers.

1. Different Ways to Add Event Handlers


Method 1: Inline Event Handlers (Not Recommended)

You can add event handlers directly in an HTML element’s attributes.

<button onclick="alert('Button Clicked!')">Click Me</button>

Method 2: Using the onclick Property (DOM Event Handling)

You can assign an event handler to an element using its event property (e.g., onclick).

let btn = document.getElementById("myButton");


btn.onclick = function() {
alert("Button clicked!");
};

Method 3: Using addEventListener() (Recommended)

The best way to add event handlers is using addEventListener().

let btn = document.getElementById("myButton");


btn.addEventListener("click", function() {
alert("Button Clicked!");
});

2. Removing Event Handlers


To remove an event handler, use removeEventListener().
function showMessage() {
alert("Hello!");
}

btn.addEventListener("click", showMessage);

// Remove event after 5 seconds


setTimeout(() => {
btn.removeEventListener("click", showMessage);
}, 5000);

3. Event Object (event)


When an event occurs, JavaScript provides an event object containing details about the event.

btn.addEventListener("click", function(event) {
console.log("Event Type:", event.type); // "click"
console.log("Clicked Element:", event.target); // <button>
});

4. Prevent Default Behavior


Some elements have default behaviors (e.g., form submission, link navigation). Use
event.preventDefault() to stop them.

document.getElementById("myLink").addEventListener("click",
function(event) {
event.preventDefault(); // Prevents link navigation
alert("Link clicked, but navigation is stopped!");
});
Validation in JavaScript
Validation in JavaScript ensures that user input meets specific criteria before submitting a form. It
helps prevent incorrect or malicious data entry.

1. Types of Validation
✅ Client-Side Validation (JavaScript)
●​ Fast (happens in the browser)
●​ Provides instant feedback
●​ Prevents unnecessary server requests

✅ Server-Side Validation (Backend – PHP, Node.js, etc.)


●​ Ensures security even if client-side validation is bypassed
●​ Validates input before processing data

2. JavaScript Form Validation Techniques


(a) Validating Required Fields
function validateForm() {
let name = document.getElementById("name").value;

if (name.trim() === "") {


alert("Name field cannot be empty.");
return false; // Prevent form submission
}
return true; // Allow form submission
}
●​ Checks if the field is empty before submitting the form.

(b) Validating Email Format

function validateEmail() {
let email = document.getElementById("email").value;
let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

if (!regex.test(email)) {
alert("Invalid email format!");
return false;
}
return true;
}
✅ Uses Regular Expressions (RegEx) to check email format.
(c) Validating Password Strength
function validatePassword() {
let password = document.getElementById("password").value;
let regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;

if (!regex.test(password)) {
alert("Password must be at least 8 characters long and include
letters & numbers.");
return false;
}
return true;
}
✅ Ensures password contains at least one letter, one number, and 8+ characters.
(d) Validating Phone Numbers
function validatePhone() {
let phone = document.getElementById("phone").value;
let regex = /^\d{10}$/; // 10-digit number

if (!regex.test(phone)) {
alert("Invalid phone number! Must be 10 digits.");
return false;
}
return true;
}
✅ Allows only 10-digit numbers.
3. Complete Form Validation Example
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
return validateName() && validateEmail() && validatePassword()
&& validatePhone();
}

function validateName() {
let name = document.getElementById("name").value;
if (name.trim() === "") {
alert("Name is required.");
return false;
}
return true;
}

function validateEmail() {
let email = document.getElementById("email").value;
let regex =
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!regex.test(email)) {
alert("Invalid email address.");
return false;
}
return true;
}

function validatePassword() {
let password = document.getElementById("password").value;
let regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
if (!regex.test(password)) {
alert("Password must be at least 8 characters long with
letters & numbers.");
return false;
}
return true;
}

function validatePhone() {
let phone = document.getElementById("phone").value;
let regex = /^\d{10}$/;
if (!regex.test(phone)) {
alert("Invalid phone number! Must be 10 digits.");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return validateForm()">
<label>Name:</label>
<input type="text" id="name"><br><br>

<label>Email:</label>
<input type="text" id="email"><br><br>

<label>Password:</label>
<input type="password" id="password"><br><br>

<label>Phone:</label>
<input type="text" id="phone"><br><br>

<button type="submit">Submit</button>
</form>
</body>
</html>
✅ Prevents form submission if validation fails.

4. HTML5 Built-in Validation (Alternative)

HTML5 provides basic validation using attributes:

<form>
<input type="text" id="name" required> <!-- Ensures field is not empty
-->
<input type="email" id="email" required> <!-- Ensures correct email
format -->
<input type="password" id="password" minlength="8" required> <!--
Minimum 8 chars -->
<input type="tel" id="phone" pattern="\d{10}" required> <!-- 10-digit
phone -->
<button type="submit">Submit</button>
</form>
✅ Simple & effective, but lacks customization.

JS Cookies
JavaScript cookies are small pieces of data stored in the browser, typically used for session
management, user preferences, or tracking. You can create, read, update, and delete cookies using
JavaScript.

Creating a Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 23:59:59
GMT; path=/";

●​ username=JohnDoe: Key-value pair.


●​ expires: Expiration date. Without it, the cookie is deleted when the session ends.
●​ path: Defines the cookie's scope (e.g., / for the whole site).
Reading a Cookie
console.log(document.cookie);

This returns all cookies as a single string:

"username=JohnDoe; theme=dark"

To extract a specific cookie:

function getCookie(name) {
let cookies = document.cookie.split("; ");
for (let cookie of cookies) {
let [key, value] = cookie.split("=");
if (key === name) return value;
}
return null;
}
console.log(getCookie("username")); // "JohnDoe"

Updating a Cookie

To update, set the same key with a new value:

document.cookie = "username=JaneDoe; expires=Fri, 31 Dec 2025 23:59:59


GMT; path=/";

Deleting a Cookie

Set the expiration date to a past time:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT;


path=/";
Accessing Important properties of HTML controls in a JavaScript

1. Text Input (<input type="text">)

Important Properties:

●​ value → Gets or sets the input value


●​ disabled → Disables the input
●​ placeholder → Placeholder text
●​ readonly → Makes the input read-only

Example:
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="getInputValue()">Get Value</button>

<script>
function getInputValue() {
let input = document.getElementById("nameInput");
alert("Value: " + input.value);
}
</script>

2. Checkbox (<input type="checkbox">)

Important Properties:

●​ checked → Returns true if checked, otherwise false


●​ disabled → Disables the checkbox

Example:
<input type="checkbox" id="agreeCheckbox"> Agree to terms
<button onclick="checkAgreement()">Check Status</button>

<script>
function checkAgreement() {
let checkbox = document.getElementById("agreeCheckbox");
alert(checkbox.checked ? "Checked" : "Not Checked");
}
</script>

3. Radio Button (<input type="radio">)

Important Properties:

●​ checked → Returns true if selected


●​ name → Groups radio buttons together

Example:
<input type="radio" name="gender" value="Male" id="male"> Male
<input type="radio" name="gender" value="Female" id="female"> Female
<button onclick="getSelectedGender()">Get Selected</button>

<script>
function getSelectedGender() {
let gender = document.querySelector('input[name="gender"]:checked');
alert(gender ? gender.value : "No selection");
}
</script>

4. Dropdown (<select>)

Important Properties:

●​ value → Gets the selected option


●​ selectedIndex → Index of selected option
●​ options → List of all options
Example:
<select id="fruitSelect">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
<button onclick="getSelectedFruit()">Get Selected</button>

<script>
function getSelectedFruit() {
let select = document.getElementById("fruitSelect");
alert("Selected: " + select.value);
}
</script>

5. Textarea (<textarea>)

Important Properties:

●​ value → Gets or sets the text inside the textarea

Example:
<textarea id="comments">This is a comment</textarea>
<button onclick="showComment()">Show Comment</button>

<script>
function showComment() {
let textarea = document.getElementById("comments");
alert(textarea.value);
}
</script>
6. Button (<button>)

Important Properties:

●​ disabled → Disables the button

Example:
<button id="submitBtn" onclick="disableButton()">Click Me</button>

<script>
function disableButton() {
document.getElementById("submitBtn").disabled = true;
}
</script>

7. File Input (<input type="file">)

Important Properties:

●​ files → Returns the selected file(s)

Example:
<input type="file" id="fileInput">
<button onclick="showFileName()">Get File</button>

<script>
function showFileName() {
let fileInput = document.getElementById("fileInput");
alert(fileInput.files.length > 0 ? fileInput.files[0].name : "No file
selected");
}
</script>

You might also like