0% found this document useful (0 votes)
6 views16 pages

Revision JS

Uploaded by

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

Revision JS

Uploaded by

dailyukshots
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Events: Handling Events, onClick, onSubmit, onLoad.

What are JavaScript Events?

An event is something that happens in the browser, like:

 Clicking a button
 Submitting a form
 Loading a webpage

We use JavaScript to handle events, meaning we decide what should happen when the event
occurs.

1. Handling Events

To handle an event, we can attach JavaScript code to an HTML element. This tells the browser:
"When this event happens, run this code."

Example:

<button onclick="sayHello()">Click Me</button>

<script>
function sayHello() {
alert("Hello, World!");
}
</script>

Explanation:

 The onclick attribute in the <button> tells the browser to run the sayHello() function
when the button is clicked.

2. Common Events

a) onClick

The onClick event is triggered when a user clicks on an element, like a button.

Example:

<button onclick="changeText()">Click Me</button>


<p id="demo">This is some text.</p>

<script>
function changeText() {
document.getElementById("demo").innerText = "You clicked the button!";
}
</script>

b) onSubmit

The onSubmit event is triggered when a form is submitted. This is useful for validating form
data.

Example:

<form onsubmit="validateForm(); return false;">


<input type="text" id="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>

<script>
function validateForm() {
let name = document.getElementById("name").value;
if (name === "") {
alert("Please enter your name.");
} else {
alert("Form submitted successfully!");
}
}
</script>

Explanation:

 onsubmit="validateForm(); return false;" prevents the form from actually


submitting if the validation fails.

c) onLoad

The onLoad event is triggered when a webpage finishes loading. You can use it to automatically
run JavaScript when the page opens.

Example:

<body onload="welcomeMessage()">
<h1>Welcome to My Website</h1>

<script>
function welcomeMessage() {
alert("The page has loaded!");
}
</script>
</body>

Understanding the DOM: Document Object Model, DOM Tree.


DOM (Document Object Model):
The DOM is like a blueprint of an HTML page. Imagine your HTML document as a structure
made of different parts (like a tree). Each part (like a <div>, <p>, <button>, etc.) is like a
branch, and the whole structure is like a tree.

DOM Tree:

 In HTML, everything is organized in a hierarchical structure. Each element in your


HTML is like a part of this tree.
 The root of this tree is the <html> tag. From there, all the other elements are branches
that connect back to it (like <body>, <head>, <div>, <span>, etc.).

How to visualize the DOM Tree?

Here’s an example of a simple HTML structure:

<html>
<head>
<title>My Page</title>
</head>
<body>
<div id="main">
<h1>Welcome to My Website!</h1>
<p>This is a paragraph.</p>
<button id="myButton">Click Me</button>
</div>
</body>
</html>

In this structure, the <html> is at the top, followed by <head> and <body>. Within <body>, there
is a <div>, which contains <h1>, <p>, and a <button>. This forms the tree-like structure of the
DOM.

What is it useful for?

The DOM helps you to access and manipulate elements in your web page using JavaScript. You
can change the content, style, and behavior of your webpage using this DOM tree.

Changing Content and Styles Dynamically with JavaScript.

JavaScript can change the content and appearance of a webpage dynamically without
reloading the page. Makes websites more interactive and responsive.

Focus of this lecture:

1. Change text and HTML content dynamically.


2. Change CSS styles dynamically.

Changing Content Dynamically

1. Method: innerHTML
o Replaces the content inside an HTML element.
o Can include plain text or HTML tags.
2. Method: textContent
o Updates text only, without interpreting HTML tags.

Example:

<h2 id="heading">Welcome to JavaScript!</h2>


<button onclick="changeHeading()">Change Heading</button>

<script>
function changeHeading() {
// Access the element by ID and change its inner content
document.getElementById("heading").innerHTML = "<b>Heading Changed!
</b>";
}
</script>

//When the button is clicked, innerHTML adds bold text to the heading.

Real-World Use Case: Updating a live cricket score or a shopping cart's total.

Changing Styles Dynamically

Using style Property: Access CSS properties directly using element.style.property.

Example:

<p id="paraStyle">This text will look fancy soon!</p>


<button onclick="changeStyle()">Change Style</button>

<script>
function changeStyle() {
let para = document.getElementById("paraStyle");
para.style.color = "blue"; // Change text color to blue
para.style.fontSize = "22px"; // Increase font size to 22px
para.style.backgroundColor = "lightyellow"; // Set background color
para.style.border = "2px dashed red"; // Add a border
}
</script>

//When the button is clicked, multiple styles like color, font size, background color, and border
are dynamically applied to the paragraph.

Combining Content and Style Changes


1. Example:

<div id="contentBox" style="width: 200px; padding: 10px; text-align:


center; border: 1px solid black;">
Click the button to see changes!
</div>
<button onclick="changeContentAndStyle()">Change Content &
Style</button>

<script>
function changeContentAndStyle() {
let box = document.getElementById("contentBox");
// Change the content
box.innerHTML = "<h3>Transformation Complete!</h3>";
// Change styles dynamically
box.style.color = "white";
box.style.backgroundColor = "green";
box.style.borderRadius = "10px"; // Add rounded corners
box.style.fontSize = "20px";
}
</script>

//The innerHTML adds new HTML content, and multiple style properties like color, background
color, and border radius are changed.

Activity for Students

Task: Create a webpage with:

o A paragraph that updates its text and style when a button is clicked.
o A div that changes its content, background color, and adds a border when clicked.

Arrays: Creating Arrays, Array Methods (push, pop, shift, unshift).


What Are Arrays?

 Arrays are special variables that can hold multiple values at the same time.
 Think of an array like a list or a collection of items (e.g., a shopping list).

How to Create Arrays

There are 2 common ways to create arrays in JavaScript:

1. Using Square Brackets ([])

This is the most common and easy way.


let fruits = ["Apple", "Banana", "Mango"]; // Array with 3 items
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]

2. Using new Array()

This is less common but works the same way.

let numbers = new Array(10, 20, 30); // Array with 3 items


console.log(numbers); // Output: [10, 20, 30]

Accessing Array Elements

 Array items are accessed using their index (position).


 Index starts at 0 (first item).

Example:

let colors = ["Red", "Green", "Blue"];


console.log(colors[0]); // Output: Red
console.log(colors[1]); // Output: Green

Common Array Methods

1. push() - Add to the End

Adds a new item to the end of the array.

let fruits = ["Apple", "Banana"];


fruits.push("Mango");
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]

2. pop() - Remove from the End

Removes the last item from the array.

let fruits = ["Apple", "Banana", "Mango"];


fruits.pop();
console.log(fruits); // Output: ["Apple", "Banana"]

3. shift() - Remove from the Start

Removes the first item from the array.

let fruits = ["Apple", "Banana", "Mango"];


fruits.shift();
console.log(fruits); // Output: ["Banana", "Mango"]

4. unshift() - Add to the Start


Adds a new item to the start of the array.

let fruits = ["Banana", "Mango"];


fruits.unshift("Apple");
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]

Quick Practice
// Step 1: Create an Array
let students = ["Ali", "Sara", "Ahmed"];

// Step 2: Add a new student to the end


students.push("Zain");
console.log(students); // ["Ali", "Sara", "Ahmed", "Zain"]

// Step 3: Remove the last student


students.pop();
console.log(students); // ["Ali", "Sara", "Ahmed"]

// Step 4: Remove the first student


students.shift();
console.log(students); // ["Sara", "Ahmed"]

// Step 5: Add a new student to the start


students.unshift("Ayesha");
console.log(students); // ["Ayesha", "Sara", "Ahmed"]

Practice Code with document.write()

1. Create index.html File:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Methods Practice</title>
</head>
<body>
<h1>Array Methods Practice</h1>
<script src="arrays.js"></script>
</body>
</html>

2. Create arrays.js File:

// Step 1: Create an Array


let students = ["Ali", "Sara", "Ahmed"];

// Step 2: Add a new student to the end


students.push("Zain");
document.write("After push: " + students + "<br>"); // Show result on the
screen

// Step 3: Remove the last student


students.pop();
document.write("After pop: " + students + "<br>"); // Show result on the
screen

// Step 4: Remove the first student


students.shift();
document.write("After shift: " + students + "<br>"); // Show result on the
screen

// Step 5: Add a new student to the start


students.unshift("Ayesha");
document.write("After unshift: " + students + "<br>"); // Show result on the
screen

Expected Output on Browser Screen:

After running the HTML file in the browser, you should see the results printed on the page like
this:

After push: Ali,Sara,Ahmed,Zain


After pop: Ali,Sara,Ahmed
After shift: Sara,Ahmed
After unshift: Ayesha,Sara,Ahmed

Basic Array Methods


Array length
Array toString()
Array at()
Array join()
Array pop()
Array push()
Array shift()
Array unshift()
Array delete()
Array concat()
Array copyWithin()
Array flat()
Array splice()
Array toSpliced()
Array slice()

Objects: Object Literals, Accessing and Modifying Properties, Methods.

What is an Object in JavaScript?

An object is a data structure that stores related data in the form of key-value pairs. It's like a
container where you group together different pieces of information under one name (the object).
Each piece of information is accessed using a key (also called a property) and the corresponding
value.

Objects are used to represent real-world entities and group related data. For example, a person
object might store a person's name, age, and address.

Difference Between a Variable and an Object:

 A variable holds a single value (like a number or string).


 An object holds multiple values (properties) together. It can contain different types of
values such as strings, numbers, arrays, or even other objects.

1. Object Literals:

An object literal is the most common way to create an object. You define it using curly braces
{}, and each property is written as key: value.

Example:

let person = {
name: "Ali",
age: 25,
isStudent: true
};

Here, person is an object that has 3 properties:

 name is the key, and "Ali" is the value.


 age is the key, and 25 is the value.
 isStudent is the key, and true is the value.
2. Accessing Object Properties:

You can access the values of an object’s properties using two methods:

a. Dot Notation:

With dot notation, you use . to access the property of the object.

console.log(person.name); // Output: "Ali"


console.log(person.age); // Output: 25

b. Bracket Notation:

With bracket notation, you use square brackets []. This is useful when the property name is
stored in a variable.

console.log(person["name"]); // Output: "Ali"


console.log(person["age"]); // Output: 25

3. Modifying Object Properties:

You can modify the value of an object property just like you would access it.

a. Using Dot Notation:

person.age = 26; // Change the age to 26


console.log(person.age); // Output: 26

b. Using Bracket Notation:

person["name"] = "Sara"; // Change the name to "Sara"


console.log(person.name); // Output: "Sara"

4. Adding New Properties to Objects:

You can also add new properties to an object.

a. Using Dot Notation:

person.city = "Lahore"; // Add a new property 'city'


console.log(person.city); // Output: "Lahore"

b. Using Bracket Notation:

javascript
Copy code
person["country"] = "Pakistan"; // Add a new property 'country'
console.log(person.country); // Output: "Pakistan"

5. Methods in Objects:

Objects can also have methods, which are functions stored as properties of the object. These
methods can perform actions using the object’s properties.

Example of an Object with a Method:

let person = {
name: "Ali",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};

person.greet(); // Output: "Hello, my name is Ali"

In this example, greet is a method of the person object. The this keyword inside the method
refers to the current object (person), so this.name refers to the name property of the person
object.

Summary:

1. Objects store multiple values (key-value pairs) together.


2. Variables store only a single value.
3. You can access object properties using dot or bracket notation.
4. You can modify and add new properties to an object.
5. Methods are functions inside an object that perform actions using its properties.

JSON: Introduction, Parsing JSON, Stringifying Objects.

JSON in JavaScript: A Short and Easy Introduction

JSON stands for JavaScript Object Notation. It's a lightweight format used for storing and
exchanging data. JSON is often used in APIs and for storing data in web applications.

1. What is JSON?

 JSON is a text format that looks like a JavaScript object but is stringified (converted into
a string).
 It's used for transmitting data between a server and a web application in a format that can
be easily parsed and generated by both.
Example of JSON:
{
"name": "Ali",
"age": 25,
"isStudent": true
}

2. Parsing JSON:

To work with JSON data, we first need to parse (convert) it into a JavaScript object. This is done
using the JSON.parse() method.

Example:

let jsonString = '{"name": "Ali", "age": 25, "isStudent": true}';


let obj = JSON.parse(jsonString); // Parse JSON string to JavaScript object

console.log(obj.name); // Output: Ali


console.log(obj.age); // Output: 25
console.log(obj.isStudent); // Output: true

3. Stringifying Objects:

If you have a JavaScript object and you want to convert it into a JSON string, you use the
JSON.stringify() method.

Example:

let person = {
name: "Ali",
age: 25,
isStudent: true
};

let jsonString = JSON.stringify(person); // Convert JavaScript object to JSON


string
console.log(jsonString); // Output: {"name":"Ali","age":25,"isStudent":true}

Key Points:

1. JSON.parse() converts a JSON string into a JavaScript object.


2. JSON.stringify() converts a JavaScript object into a JSON string.

Why is JSON useful?

 It allows you to send data between a server and client.


 It's easy to read and write for both humans and machines.
Understanding Asynchronous JavaScript: Callbacks, Event Loop, and
Concurrency

JavaScript can handle tasks that take time (like loading data from a server) without stopping the
rest of the code. This is called asynchronous programming. Let’s break it into simple parts.

1. What is Synchronous vs. Asynchronous?

Synchronous

In synchronous programming, one task must finish before the next starts.
Example:

console.log("Task 1");
console.log("Task 2");
console.log("Task 3");

Output:

Task 1
Task 2
Task 3

Each task runs in order, one at a time.

Asynchronous

In asynchronous programming, some tasks take time, but JavaScript does not wait for them. It
moves to the next task while waiting for the first one to complete.
Example:

console.log("Task 1");
setTimeout(() => console.log("Task 2 (after 2 seconds)"), 2000);
console.log("Task 3");

Output:

Task 1
Task 3
Task 2 (after 2 seconds)

Here, setTimeout is an asynchronous function that waits for 2 seconds but doesn’t block the rest
of the code.
2. What is a Callback?

A callback is a function that is passed to another function and gets executed after that
function is done with its task.

Explanation with Example:

Let's say you ask a friend to give you a call when they finish work. While they are working,
you can do other things. When they are done, they will call you (this is the callback).

// The greet function takes a name and a callback function

function greet(name, callback) {

// The callback is called with a greeting message

callback(`Hello, ${name}!`);

// Calling greet with "Alice" and console.log as the callback

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

3. What is the Event Loop?

The event loop is the mechanism that allows JavaScript to handle asynchronous tasks. It:

1. Runs the main code first (synchronous tasks).


2. Waits for asynchronous tasks to complete in the background.
3. Executes their callbacks once the main code is done.

Example:

console.log("Start");

setTimeout(() => console.log("Async Task"), 2000);

console.log("End");

How it works:

1. "Start" is printed.
2. setTimeout starts a timer and moves to the background.
3. "End" is printed.
4. After 2 seconds, the callback (console.log("Async Task")) is added to the queue and
then executed.

Output:

Start
End
Async Task

4. What is Concurrency?

Concurrency means JavaScript can manage multiple tasks at the same time using its event loop.
While one task is waiting (e.g., fetching data), JavaScript can process other tasks.

Example:

Imagine you’re cooking:

1. You boil water (task starts).


2. While water boils, you chop vegetables (another task).
3. When the water is ready, you use it to cook (callback).

Code Example:

console.log("Boiling water...");
setTimeout(() => console.log("Water is ready!"), 3000);

console.log("Chopping vegetables...");
console.log("Vegetables are ready!");

Output:

Boiling water...
Chopping vegetables...
Vegetables are ready!
Water is ready!

5. Real-Life Example with Code

Let’s simulate fetching user data:

function getUserData(userId, callback) {


console.log("Fetching user data...");
setTimeout(() => {
const user = { id: userId, name: "John" };
callback(user);
}, 2000);
}

getUserData(1, (user) => {


console.log("User data received:", user);
});

Output:

Fetching user data...


User data received: { id: 1, name: "John" }

You might also like