Java Script
Java Script
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.
//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
1. Arithmetic Operators
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]);
}
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");
// 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“
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:
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.
(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).
<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>
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.
// OR
element.parentNode.removeChild(element); //
Traditional way
7. Event Handling Methods
Attach actions when users interact with elements.
<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!";
});
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.
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.
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:
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>