0% found this document useful (0 votes)
11 views90 pages

Java Script

Basic Javascript

Uploaded by

amarjeet.rai
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)
11 views90 pages

Java Script

Basic Javascript

Uploaded by

amarjeet.rai
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/ 90

Unit2:

Java Script Client side scripting using java script, Introduction to java script,
internal and external Java script files, variables, control statements, loops,
Arrays , string handling , How to write functions in JavaScript, inputting and
outputting from form elements to JavaScript. DOM concept, creating html
elements using java script. Drawing 2D shapes, handling events. Introduction
to AJAX
JavaScript is a high-level, dynamically typed programming language
primarily known for enabling interactive and dynamic content on web
pages.
Characteristics of JavaScript:
1. Lightweight and Interpreted:
JavaScript code does not need compilation; it is interpreted by the browser at
runtime.
Makes execution faster and easier for web applications.
2. Object-Oriented (Prototype-Based):
JavaScript supports objects, but it is prototype-based, not class-based like Java
or C++.
ES6 introduced class syntax, but internally it still works with prototypes.
3. Dynamic Typing:
Variables in JavaScript are not bound to a specific data type.
Example:
let x = 10; // number
x = "Hello"; // string
4. Case-Sensitive
JavaScript differentiates between uppercase and lowercase letters.
Example: Variable and variable are different.

5. Platform Independent
JavaScript is supported on all major browsers and operating systems.
Code written once can run anywhere (with minor compatibility checks).

6. Event-Driven
JavaScript responds to events (e.g., button clicks, mouse movements, form
submissions).
Enables interactive web pages.

7. Single-Threaded but Asynchronous


JavaScript uses a single-threaded execution model.
With the help of callbacks, promises, and async/await, it handles asynchronous
tasks like fetching data without blocking execution.
8. Functional Programming Support
Functions are treated as first-class citizens (can be assigned to variables,
passed as arguments, and returned).
Example:
function greet() { return "Hi"; }
let sayHello = greet;
console.log(sayHello());

9. Client-Side and Server-Side Use


Traditionally used for client-side scripting.
With Node.js, JavaScript can also run on the server side.

10. Loose Syntax but Powerful


Flexible syntax (missing semicolons still works in many cases).
Powerful features like closures, hoisting, and event loops.
What is Prototype-Based?
In JavaScript, objects inherit properties and methods from other objects using something called a
prototype.
Every object in JavaScript has a hidden property called [[Prototype]] (accessible via __proto__ in most
environments).
// Create an object
let car = {
brand: "Toyota",
start: function() {
console.log(this.brand + " is starting...");
}
};

// Create another object that inherits from car


let myCar = Object.create(car);
myCar.brand = "Honda";
myCar.start(); // Output: Honda is starting...

//myCar didn’t have its own start() method, but it inherited it from car through the prototype.
How Prototype Chain Works:
• When you try to access a property/method:
• JavaScript first looks in the object itself.
• If not found, it looks at the object’s prototype.
• If still not found, it goes up the prototype chain until it reaches Object.prototype.

function Person(name) {
this.name = name;
}
// Adding method to prototype
Person.prototype.greet = function() {
console.log("Hello, I'm " + this.name);
};
let p1 = new Person("Alice");
let p2 = new Person("Bob");
p1.greet(); // Hello, I'm Alice
p2.greet(); // Hello, I'm Bob

Note: Instead of copying greet() into every object, all objects share the same method through the
prototype.
1. Internal JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Internal JS Example</title>
<script>
function greet() {
alert("Hello from Internal JavaScript!");
}
</script>
</head>
<body>
<button onclick="greet()">Click Me</button>
</body>
</html>
2. External JavaScript:
• JavaScript code is written in a separate .js file.
• That file is linked to the HTML using the <script src="filename.js"></script> tag.
• Best for reusability, clean code, and maintenance.
<!DOCTYPE html>
<html>
<head>
<title>External JS Example</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="greet()">Click Me</button>
</body>
</html>

script.js
-------------------
function greet() {
alert("Hello from External JavaScript!");
}
Declaring Variables in JavaScript:
1. var (Old way)
Function-scoped (visible only inside the function where declared).
Allows re-declaration and hoisting (moved to top before execution).
Not recommended in modern JS.
var x = 10;
var x = 20; // ✅ allowed
console.log(x); // 20

2. let (Modern way)


Block-scoped (works only inside {} block).
Cannot be redeclared in the same scope.
Safer and widely used today.
let y = 10;
y = 15; // ✅ allowed
// let y = 20; // ❌ Error (cannot redeclare in same scope)
3. const (Constant)
• Block-scoped.
• Value cannot be changed (immutable).
• Must be assigned at the time of declaration.
const PI = 3.1416;
// PI = 3.14; // ❌ Error

Rules for Naming Variables:


• Must start with a letter, _, or $.
• Cannot start with a number.
• Case-sensitive (age ≠ Age).
• Reserved words (like let, var, const, function) cannot be used as
variable names.
Types of Operators in JavaScript:

1. Arithmetic Operators

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
** 2 ** 3 8
(power)
++ Increment let a=5; a++ 6
-- Decrement let a=5; a-- 4
2. Assignment Operators

Operator Example Same as


= x = 5 assign value
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
**= x **= 2 x = x ** 2
3. Comparison Operators

Operator Description Example Result


== Equal to (value only) 5 == "5" true
=== Strict equal (value + type) 5 === "5" false
!= Not equal (value only) 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 5 >= 5 true
<= Less than or equal 5 <= 4 false
4. Logical Operators

Operator Description Example Result


(5 > 3 &&
&& AND → true if both true true
10 > 8)
|| OR → true if one is true (5 > 3 || 5>8) true
! NOT → reverses result !(5 > 3) false
5. Bitwise Operators (work on binary values)

Operator Name Example


& AND 5 & 1 → 1
| OR 2 | 1 → 3
^ XOR 5 ^ 1 → 4
~ NOT ~5 → -6
<< Left shift 5 << 1 → 10
>> Right shift 5 >> 1 → 2
6. Ternary Operator (?:)

let age = 18;


let result = (age >= 18) ? "Adult" : "Minor";
console.log(result); // "Adult"
7. Type Operators

Operator Description Example


typeof Returns type of variable typeof "hello" → "string"
Checks if an object is an instance arr instanceof Array →
instanceof
of a class true
Control Statements in JavaScript:
Control statements decide the flow of execution in a program.

1. Conditional Statements (Decision Making):


let age = 20;
if (age >= 18) {
console.log("You are an adult");
}

let marks = 40;


if (marks >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
let score = 75;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else if (score >= 50) {
console.log("Grade C");
} else {
console.log("Fail");
}
switch (day) {
case 1: console.log("Monday"); break;
case 2: console.log("Tuesday"); break;
case 3: console.log("Wednesday"); break;
default: console.log("Invalid day");
}
2. Looping Statements (Repetition):
for (let i = 1; i <= 5; i++) {
console.log("Number: " + i);
}
let i = 1;
while (i <= 5) {
console.log("Count: " + i);
i++;
}

let i = 1;
do {
console.log("Value: " + i);
i++;
} while (i <= 5);
for…in loop (used for objects):
let student = {name: "John", age: 20, grade: "A"};
for (let key in student) {
console.log(key + " : " + student[key]);
}

for…of loop (used for arrays, strings, iterables):


let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
3. Jump Statements:
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i); // 1, 2
}

for (let i = 1; i <= 5; i++) {


if (i === 3) continue;
console.log(i); // 1, 2, 4, 5
}
What is an Array?
In JavaScript, an array is a data structure used to store multiple values in a
single variable.
•It is an ordered collection.
•An array can store numbers, strings, objects, functions, or even other
arrays.
Ways to Create Arrays:
1. Using square brackets [] (most common)
let fruits = ["apple", "banana", "mango"];
console.log(fruits); // ["apple", "banana", "mango"]

2. Using new Array()


let numbers = new Array(10, 20, 30);
console.log(numbers); // [10, 20, 30]
What is a String in JavaScript?
• A string is a sequence of characters used to represent text.
• In JavaScript, strings are written inside single quotes ('), double quotes (") or
backticks (` for template literals).

Example:
let str1 = "Hello";
let str2 = 'World';
let str3 = `Hello, ${str2}!`; // Template literal
String Creation
let msg = "Hello JavaScript";
let msg = new String("Hello JavaScript");

Property Description Example


Returns the number of
length "Hello".length → 5
characters
Important String Methods:

let str = "JavaScript";


console.log(str[0]); // J
console.log(str.charAt(4)); // S

let text = "Hello JavaScript";


console.log(text.indexOf("Java")); // 6 (first occurrence)
console.log(text.lastIndexOf("a")); // 9 (last occurrence)
console.log(text.includes("Hello")); // true
console.log(text.startsWith("Hell")); // true
console.log(text.endsWith("Script")); // true
let str = "JavaScript";

// slice(start, end)
console.log(str.slice(0, 4)); // "Java"
// substring(start, end)
console.log(str.substring(4, 10)); // "Script"
// substr(start, length) [deprecated, but still works]
console.log(str.substr(4, 6)); // "Script“

let str = "hello world";


console.log(str.toUpperCase()); // "HELLO WORLD"
console.log(str.toLowerCase()); // "hello world"
console.log(str.replace("world", "JS")); // "hello JS"
console.log(str.replaceAll("l", "x")); // "hexxo worxd"
let str = " JavaScript ";
console.log(str.trim()); // "JavaScript"
console.log(str.trimStart()); // "JavaScript "
console.log(str.trimEnd()); // " JavaScript“

let str = "apple,banana,cherry";


let fruits = str.split(",");
console.log(fruits); // ["apple", "banana", "cherry"]

let joined = fruits.join(" - ");


console.log(joined); // "apple - banana - cherry"
Template Literals:
let name = “Ajay";
let age = 21;

let message = `Hello, my name is ${name}.


I am ${age} years old.`;

console.log(message); // Hello, my name is Ajay.


Escape Characters in Strings

Code Meaning
\' Single quote
\" Double quote
\\ Backslash
\n New line
\t Tab
\b Backspace
What is a Function in JavaScript?
• A function is a block of reusable code designed to perform a specific task.
• It helps avoid repetition and makes programs modular and easier to
manage.
• Functions can take input (parameters) and return output (result).

Syntax of a Function:
function functionName(parameters) {
// code block
return value; // optional
}
Types of Functions in JavaScript:

1. Named Function (Function Declaration)


A function that has a name and can be reused.

function greet(name) {
return "Hello, " + name;
}
console.log(greet(“Ramesh")); // Hello, Ramesh
2. Anonymous Function
A function without a name, often used inside variables or
callbacks.

let show = function() {


console.log("This is an anonymous function");
};

show(); // Output: This is an anonymous function


3. Arrow Function
A shorter syntax for function expressions.

const multiply = (a, b) => a * b;


console.log(multiply(3, 7)); // 21

4. Immediately Invoked Function Expression (IIFE)


A function that runs immediately after it is defined.

(function() {
console.log("IIFE runs automatically!");
})();
5. Higher-Order Function
A function that takes another function as argument or returns a
function.
Example:
function operation(fn, x, y) {
return fn(x, y);
}
function sum(a, b) { return a + b; }
function product(a, b) { return a * b; }

console.log(operation(sum, 5, 3)); // 8
console.log(operation(product, 5, 3)); // 15
6. Callback Function
A function passed as an argument to another function.

function fetchData(callback) {
console.log("Fetching data...");
callback(); // execute after task
}

fetchData(function() {
console.log("Data fetched successfully!");
});
Feature Higher-Order Function (HOF) Callback Function
A function that is
A function that takes another
passed as an
Definition function as input or returns or
argument to another
both a function.
function.
"Child" function that
"Parent" function that uses or
Role gets executed by the
returns other functions.
higher-order function.
Who Calls It is called inside the
The programmer defines it.
It? higher-order function.
7. Constructor Function
Used to create objects (similar to classes).

function Person(name, age) {


this.name = name;
this.age = age;
}

let p1 = new Person(“Ramesh", 21);


console.log(p1.name); // Ramesh
Ways of Getting Input from Form Elements:
1. Using getElementById:
• Each form element has a unique id.
• Use .value to get the entered value.
<input type="text" id="username" placeholder="Enter name">
<button onclick="getInput()">Submit</button>

<script>
function getInput() {
let name = document.getElementById("username").value;
console.log("Name:", name);
}
</script>
2. Using getElementsByName
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<button onclick="getGender()">Submit</button>

<script>
function getGender() {
let genders = document.getElementsByName("gender");
for (let g of genders) {
if (g.checked) {
console.log("Selected Gender:", g.value);
}
}
}
</script>
3. Using getElementsByTagName:
<form id="myForm">
<input type="text" placeholder="Name">
<input type="number" placeholder="Age">
<input type="email" placeholder="Email">
<button type="button" onclick="getAll()">Submit</button>
</form>
<script>
function getAll() {
let inputs = document.getElementsByTagName("input");
for (let input of inputs) {
console.log(input.value);
}
}
</script>
4. Using querySelector / querySelectorAll:
• querySelector → returns first match
• querySelectorAll → returns all matches
<input type="text" id="username" value=“Rameh">
<input type="password" class="pwd" value="12345">
<button onclick="getData()">Submit</button>

<script>
function getData() {
let user = document.querySelector("#username").value; // by ID
let pass = document.querySelector(".pwd").value; // by class
console.log("Username:", user, "Password:", pass);
}
</script>
5. Using forms[] Collection:
We can access a form and its inputs using the document.forms collection.
<form name="loginForm">
<input type="text" name="user" placeholder="Username">
<input type="password" name="pass" placeholder="Password">
<button type="button" onclick="login()">Login</button>
</form>

<script>
function login() {
let uname = document.forms["loginForm"]["user"].value;
let pwd = document.forms["loginForm"]["pass"].value;
console.log("User:", uname, "Password:", pwd);
}
</script>
6. Using Event Object (event.target):

<form id="regForm">
<input type="text" name="fullname" placeholder="Full Name">
<button type="submit">Submit</button>
</form>

<script>
document.getElementById("regForm").addEventListener("submit",
function(e) {
e.preventDefault(); // stop page reload
console.log("Name:", e.target.fullname.value);
});
</script>
What is DOM?
• The DOM (Document Object Model) is a programming interface for
web documents (HTML or XML).
• It represents the structure of a web page as a tree of objects.
• Each element (like <p>, <div>, <h1>, etc.), attribute, and text in
the HTML document becomes a node in this tree.
• The HTML DOM can be accessed with JavaScript
(and with other programming languages).
• In the DOM, all HTML elements are defined
as objects.
• A property is a value that you can get or set (like
changing the content of an HTML element).
• A method is an action you can do (like add or
deleting an HTML element).
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>

In the example above, getElementById is a method, while innerHTML is


a property.
• DOM allows JavaScript to interact with and manipulate the content,
structure, and style of a webpage dynamically.

How it Works:
• Browser loads an HTML page.
• It creates a DOM Tree representation of that page.
• JavaScript can use the DOM to:
• Access elements (e.g., a <p> or <div>).
• Change content (text, HTML).
• Modify styles (CSS).
• Add or remove elements dynamically.
• Handle user events (like button clicks, mouse moves, key
presses).
DOM Methods in JavaScript:
The DOM (Document Object Model) provides many built-in methods to
interact with a webpage.
1. Finding/Selecting Elements:
These methods help us access elements from the DOM.
document.getElementById("myId");
Returns the element with a specific id.

document.getElementsByClassName("myClass");
Returns a collection (HTMLCollection) of elements with that class.
document.getElementsByTagName("p");
Returns all <p> elements.

Using CSS Selectors:

document.querySelector(".myClass"); // First match


document.querySelectorAll("p.myClass"); // All matches
2. Changing Content:
• Once you select an element, you can change its content.

•Change HTML content


document.getElementById("demo").innerHTML = "New
Content!";
•Change text only
document.getElementById("demo").innerText = "Only
text, no HTML.";
3. Changing Attributes:
You can get or set element attributes.

let img = document.getElementById("myImage");


img.setAttribute("src", "newpic.jpg");
// Change image source

let srcValue = img.getAttribute("src");


// Get attribute value
4. Changing Styles
Modify CSS directly using JavaScript.
document.getElementById("demo").style.color = "red";
document.getElementById("demo").style.fontSize =
"20px";
5. Creating and Adding Elements
You can dynamically create new HTML elements.
let newPara = document.createElement("p");
// Create <p>
newPara.innerText = "This is a new paragraph.";
document.body.appendChild(newPara);
// Add to body
Example : Create Image element using Javascript
<!DOCTYPE html>
<html><head><title>Image Example</title></head>
<body>
<div id="container"></div>
<script>
// create image
let img = document.createElement("img");
img.setAttribute("src", "https://via.placeholder.com/150");
img.setAttribute("alt", "Sample Image");
// add image into container div
document.getElementById("container").appendChild(img);
</script>
</body>
</html>
6. Removing Elements
let element = document.getElementById("demo");
element.remove(); // Direct remove (modern way)

// OR
element.parentNode.removeChild(element); //
Traditional way
7. Event Handling Methods
Attach actions when users interact with elements.

Inline Event Handling:


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

// Clicking the button will show an alert.


Event Handling Using JavaScript Property:
<!DOCTYPE html>
<html>
<body>
<button id="myBtn">Click Me</button>
<script>
let btn = document.getElementById("myBtn");
btn.onclick = function() {
alert("Button Clicked!");
};
</script>
</body>
</html>
Here, we assign a function to the onclick property.
Event handling Using addEventListener():
<!DOCTYPE html>
<html>
<body>
<button id="myBtn">Click Me</button>
<script>
let btn = document.getElementById("myBtn");
btn.addEventListener("click", function() {
alert("Button Clicked using addEventListener!");
});
</script>
</body>
</html>
Mouse Events:
•click → Fires when an element is clicked
•dblclick → Fires on double-click
•mouseover → When the mouse pointer enters an element
•mouseout → When the mouse pointer leaves an element
•mousemove → When the mouse moves over an element
•mousedown → When a mouse button is pressed down
•mouseup → When a mouse button is released
•contextmenu → Right-click on an element
<!DOCTYPE html>
<html>
<head>
<title>Mouse Event Example</title>
</head>
<body>
<button id="btn">Click Me</button>
<p id="msg"></p>

<script>
document.getElementById("btn").addEventListener("click", function() {
document.getElementById("msg").innerText = "Button was clicked!";
});
</script>
</body>
</html>
2. Keyboard Events:
•keydown → When a key is pressed down
•keypress → When a key is pressed (deprecated in some browsers, use
keydown)
•keyup → When a key is released
<!DOCTYPE html>
<html>
<head><title>Keyboard Event Example</title></head>
<body>
<input type="text" id="textBox" placeholder="Type something here">
<p id="msg"></p>
<script>
let textBox = document.getElementById("textBox");
let msg = document.getElementById("msg");

// keydown event
textBox.addEventListener("keydown", function(event) {
msg.innerText = "Key Pressed: " + event.key;
});
</script>
</body>
</html>
3. Form & Input Events:
•submit → When a form is submitted
•reset → When a form is reset
•change → When the value of input, select, or textarea changes
•input → When the user types into an input field
•focus → When an element gets focus (e.g., user clicks inside input)
•blur → When an element loses focus
•select → When text inside an input/textarea is selected
<!DOCTYPE html>
<html><head><title>Form & Input Event Example</title></head>
<body>
<form id="myForm">
<label>Enter Name: </label><input type="text" id="nameInput" placeholder="Type your name">
<button type="submit">Submit</button>
</form>
<p id="msg"></p>
<script>
let nameInput = document.getElementById("nameInput");
let msg = document.getElementById("msg");
let form = document.getElementById("myForm");
// input event (triggers whenever text changes in the box)
nameInput.addEventListener("input", function() {msg.innerText = "Typing: " + nameInput.value;});
// form submit event
form.addEventListener("submit", function(event) {
event.preventDefault(); // stops page refresh
msg.innerText = "Form Submitted! Name: " + nameInput.value;
});
</script></body></html>
4. Window & Document Events:
• load → When the page or image is fully loaded
• DOMContentLoaded → When HTML is fully loaded and parsed
• unload → When the page is unloaded
• resize → When the window is resized
• scroll → When the page or element is scrolled
• error → When an error occurs while loading
<!DOCTYPE html>
<html><head><title>Window & Document Events</title></head>
<body>
<p id="msg"></p>
<script>
let msg = document.getElementById("msg");
// Window load event
window.addEventListener("load", function() {
msg.innerText = "Window Loaded!";
});

// Document click event


document.addEventListener("click", function() {
msg.innerText = "Document was clicked!";
});
</script>
</body>
</html>
5. Clipboard Events
• copy → When content is copied
• cut → When content is cut
• paste → When content is pasted
<!DOCTYPE html>
<html>
<head><title>Clipboard Events Example</title></head>
<body>
<input type="text" id="textBox" value="Copy or Paste here">
<p id="msg"></p>
<script>
let textBox = document.getElementById("textBox");
let msg = document.getElementById("msg");
// Copy event
textBox.addEventListener("copy", function() { msg.innerText = "Text
copied!"; });
// Cut event
textBox.addEventListener("cut", function() { msg.innerText = "Text cut!"; });
// Paste event
textBox.addEventListener("paste", function() { msg.innerText = "Text
pasted!"; });
</script>
</body>
</html>
6. Drag & Drop Events
• dragstart → When dragging starts
• drag → While dragging is happening
• dragend → When dragging ends
• dragenter → When dragged item enters a drop zone
• dragover → While dragged item is over a drop zone
• dragleave → When dragged item leaves a drop zone
• drop → When dragged item is dropped
<!DOCTYPE html>
<html>
<head><title>Mini Drag & Drop Example</title></head>
<body>
<div id="dragItem" draggable="true" style="width:80px; height:80px; background:skyblue; text-
align:center;
line-height:80px; cursor:grab;"> Drag Me</div>
<div id="dropZone" style="width:150px; height:120px; border:2px dashed black; margin-top:20px; text-
align:center;
line-height:120px;">Drop Here</div>
<script>
let dragItem = document.getElementById("dragItem");
let dropZone = document.getElementById("dropZone");
dragItem.addEventListener("dragstart", () => { console.log("Dragging started!"); });
dropZone.addEventListener("dragover", (event) => { event.preventDefault(); // allow drop
console.log("Dragging over drop zone..."); });
dropZone.addEventListener("drop", (event) => { event.preventDefault();
console.log("Item dropped!");});
</script>
</body>
</html>
7. Media Events (Audio/Video)
• play → When media starts playing
• pause → When media is paused
• ended → When media has ended
• volumechange → When volume is changed
• timeupdate → When playback position changes
• loadeddata → When media data is loaded
<!DOCTYPE html>
<html>
<head><title>Media Events Example</title></head>
<body>
<h3>Media Events Example</h3>
<video id="myVideo" width="320" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
<p id="msg"></p>
<script>
let video = document.getElementById("myVideo");
let msg = document.getElementById("msg");
// Play event
video.addEventListener("play", () => { msg.innerText = "Video started playing!"; });
// Pause event
video.addEventListener("pause", () => { msg.innerText = "Video paused!"; });
// Ended event
video.addEventListener("ended", () => { msg.innerText = "Video ended!"; });
</script>
</body>
</html>
8. Touch Events (Mobile/Tablet):
• touchstart → Finger touches the screen
• touchmove → Finger moves on the screen
• touchend → Finger is removed from screen
• touchcancel → Touch is interrupted
<!DOCTYPE html>
<html>
<head>
<title>Touch Events</title>
</head>
<body>
<div id="box" style="width:150px;height:150px;background:skyblue;line-height:150px;text-
align:center;">Touch Me</div>
<script>
let box = document.getElementById("box");
box.addEventListener("touchstart", () => {
box.innerText = "Touch Start";
});

box.addEventListener("touchend", () => {
box.innerText = "Touch End";
});
</script>
</body>
</html>
Drawing 2D shapes:
HTML5 introduced the <canvas> element, which provides a surface (like a
drawing board) for rendering graphics using JavaScript.
With JavaScript, we can draw shapes, text, images, and even animations
inside the canvas.

<canvas id="myCanvas" width="400" height="300" style="border:1px


solid black;"></canvas>

JavaScrpt:
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); // 2D drawing context
ctx (context) is the main object that provides all drawing methods.
<!DOCTYPE html>
<html>
<head><title>2D Shape Example</title></head>
<body>
<canvas id="myCanvas" width="300" height="200" style="border:1px solid black;"></canvas>
<script>
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
// Draw a circle
ctx.beginPath();
ctx.arc(150, 100, 50, 0, 2 * Math.PI); // (x, y, radius, startAngle, endAngle)
ctx.fillStyle = "skyblue";
ctx.fill();
ctx.stroke();
</script>
</body>
</html>
The CanvasRenderingContext2D object (usually named ctx) provides all the
methods and properties used for drawing in HTML5 canvas.
1. Rectangles
fillRect(x, y, width, height) → draws a filled rectangle.
strokeRect(x, y, width, height) → draws only the rectangle border.
clearRect(x, y, width, height) → clears part of the canvas (makes it transparent).
2. Paths (Lines & Shapes)
beginPath() → starts a new path (drawing).
moveTo(x, y) → moves the “pen” to a new starting point.
lineTo(x, y) → draws a line from the current position to given coordinates.
closePath() → closes the shape by drawing a straight line back to the start.
stroke() → outlines the path.
fill() → fills the path with color.

3. Circles & Arcs


arc(x, y, radius, startAngle, endAngle) → draws an arc or circle.
(Angles are in radians, degrees: 360° = 2π radians).
4. Colors & Styles
fillStyle = "color" → sets fill color.
strokeStyle = "color" → sets stroke (border) color.
lineWidth = number → sets line thickness.

5. Text
fillText(text, x, y) → draws filled text.
strokeText(text, x, y) → draws outlined text.
font = "style size family" → sets text font.

6. Images
drawImage(image, x, y, width, height) → draws an image on the
canvas.
What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It is a technique in web development that allows a web page to send and
receive data from a server without reloading the entire page.

Features of AJAX
Asynchronous → The page does not refresh; data updates happen in the
background.
Uses JavaScript → to control the request/response.
Data formats → Can exchange data in XML, JSON, or plain text (JSON is
most common today).
Works with HTTP requests → like GET and POST.
How AJAX Works (Step by Step)
• User does something (e.g., clicks a button).
• JavaScript creates an XMLHttpRequest (or uses fetch API).
• Request is sent to the server.
• Server processes the request and sends back data (XML/JSON/text).
• JavaScript updates part of the webpage with the new data — without
reloading the whole page.
What is XMLHttpRequest?
XMLHttpRequest is a JavaScript object used in AJAX to request data
from a server without reloading the page.
• It was the first API for AJAX.
• Works in all browsers.
• Can make both synchronous (blocking) and asynchronous (non-blocking)
HTTP requests.
Basic Steps to Use XMLHttpRequest:

• Create an XMLHttpRequest object


let xhr = new XMLHttpRequest();

• Initialize the request using open()


Syntax: xhr.open(method, URL, async)
method: "GET" or "POST" (HTTP method)
URL: The path to the server resource
async: true (asynchronous, default) or false (synchronous)
Set request headers:
Usually used in POST requests.
xhr.setRequestHeader("Content-Type", "application/json");

Define a callback function to handle the response:


xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText); // Response from server
}
};

Send the request


xhr.send();
let xhr = new XMLHttpRequest();

xhr.open("GET", "data.json", true);

xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Response:", xhr.responseText);
}
};
xhr.send();
<button id="btn">Load</button>
<pre id="out"></pre>
<script>
document.getElementById('btn').addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
var data = JSON.parse(xhr.responseText);
document.getElementById('out').textContent = JSON.stringify(data, null, 2);
} else {
document.getElementById('out').textContent = 'Request failed: ' + xhr.status;
}
} };
xhr.send();
}); </script>
What is fetch()?
It is a built-in JavaScript function for making asynchronous requests

Syntex:
fetch(url, options)
.then(response => {
// handle response
})
.catch(error => {
// handle error
});
<!DOCTYPE html>
<html><head> <title>Fetch Example</title></head>
<body><h2>Fetch API Example</h2>
<button id="loadBtn">Load Data</button>
<div id="output"></div>
<script>
const button = document.getElementById("loadBtn");
const output = document.getElementById("output");

button.addEventListener("click", () => {
// Simple GET request using fetch
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // Convert response to JSON
.then(data => {
// Display data in the div
output.innerHTML = `<p><strong>Title:</strong> ${data.title}</p>
<p><strong>Body:</strong> ${data.body}</p>`;
})
.catch(error => {
output.innerHTML = `<p style="color:red">Error: ${error}</p>`;
});
});
</script></body></html>

You might also like