JavaScript
Introduction
Introduction
JavaScript is one of the most widely used programming languages in the world, mainly for building interactive and dynamic websites. It is often called “The Language of the Web” because it runs inside the browser, allowing developers to add behavior to static HTML pages.
History of JavaScript
| History of JavaScript | |
|---|---|
| Developed By | Brendan Eich |
| When & Where | In 1995 at Netscape Communications |
| Original purpose | To add interactivity and dynamic features to web pages. |
| Initial Names | Originally called Mocha, then changed to LiveScript, and finally named as JavaScript. |
| Why Java in the name? | Netscape partnered with Sun Microsystems to market JavaScript as a companion to Java. Java was popular at the time, so the name helped in promotion. But JavaScript and Java are completely different languages. |
| Early Development (1996-1999) | |
| In 1996 | Microsoft created JScript (their own JavaScript version) for Internet Explorer. |
| Problem | Different browsers had incompatible implementations → Developers had to write separate code for each browser. |
| In 1997 | ECMA International standardized JavaScript as ECMAScript (ES). |
| Stagnation Period (2000-2008) | |
| Browsers implemented JavaScript differently, leading to the term “Cross-browser incompatibility”. | |
| Development slowed due to lack of agreement among browser vendors. | |
| JavaScript was mainly used for small form validations and simple animations. | |
| Revival and Modern Era (2009 to At Present) | |
| 2009 – ECMAScript 5 (ES5) |
|
| 2015 – ECMAScript 6 (ES6 / ES2015)((Biggest update in JavaScript history) |
|
| ES2016 | includes() method, exponentiation operator ** |
| ES2017 | async/await |
| ES2018 | Rest/Spread in objects, asynchronous iteration |
| ES2019 | flat(), flapmap() |
| ES2020 | Optional Chaining ?., Nullish Coalescing ?? |
| ES2021–2024 | Logical Assignment Operators, Top-level await, Array.prototype.at(), and more. |
Features of JavaScript
Lightweight and fast
Object-based (supports OOP features)
Interpreted language (no need for compilation)
Event-driven (responds to user events)
Cross-platform compatible
First-class functions (functions can be assigned to variables, passed as arguments)
Uses of JavaScript
- Form validation
- Creating interactive UI/UX
- DOM manipulation
- Games and animations
- AJAX (Asynchronous Web Requests)
- Backend development (using Node.js)
Role of JavaScript in Modern Web Development
| Role of JavaScript in Modern Web Development | |
|---|---|
| Client-Side Scripting |
|
| Server-Side Development |
|
| Full Stack Development |
|
| Mobile App Development |
|
| Desktop Applications | Electron.js enables building cross-platform desktop apps (e.g., VS Code, Slack). |
| Game Development | HTML5 Canvas + JavaScript for browser games. Libraries like Phaser.js make game creation easier. |
How to include JavaScript in HTML
JavaScript can be added to an HTML document in three main ways:
Inline JavaScript
Code is written directly inside an HTML tag using the onclick, onmouseover, or other event attributes. Used for small, quick scripts.
Syntax:
<button onclick=”alert(‘Hello!’)”>Click Me</button>
Internal JavaScript
Code is written inside <script> tags within the HTML file, usually inside the <head> or <body> section. Suitable for page-specific scripts.
Syntax:
<script>
document.write("Welcome to JavaScript!");
</script>
External JavaScript
Code is placed in a separate .js file and linked to the HTML page using the <script src="filename.js"></script> tag. Helps in code reusability and better organization.
Setting up the JavaScript Environment
JavaScript can run in two main places:
Browser :
For web pages, DOM manipulation, and interactive UI.
Server / Local Machine (via Node.js)
For backend apps, scripts, and tools.
2025 Update:
Modern browsers now fully support ES2023+ features, and Node.js LTS 22+ is stable with built-in test runner,
fetch API, and top-level await.
Using the Browser Console:
Purpose: Quick testing, debugging, and DOM inspection.
Open your preferred browser (Chrome, Edge, or Firefox).
Press:
Windows/Linux:Ctrl + Shift + J
Mac:Cmd + Option + JThis opens Developer Tools → Console tab, then type
console.log("Hello, JavaScript 2025!");
const numbers = [1, 2, 3];
console.log(numbers.at(-1)); // Last element
document.body.style.background = "lightblue";
Setting up Visual Studio Code (VS Code)
Purpose: Professional code editing with syntax highlighting, extensions, and integrated terminal.
Steps:
Download from https://code.visualstudio.com
Install with Add to PATH option checked.
Open VS Code →
File→Open Folder→ select your project folder.
Recommended Extensions (2025)
ESLint – Linting and error detection.
Prettier – Code formatting.
JavaScript (ES6+) Snippets – Faster coding.
Live Server – Auto-refresh browser during development.
Code Spell Checker – Avoid typos.
Ways to implement JavaScript code in HTML.
No. of ways
There are 3 ways to implement JavaScript in HTML.
- inline
- internal
- external
Inline Implementation
Inline JavaScript Example
Inline JavaScript means writing JavaScript code directly inside an HTML element’s event attribute (e.g., onclick, onmouseover, onchange).
Syntax:
<tag event=”JavaScript Code”></tag>
In the above syntax…
tag: Any HTML tag like h1, p, button,...
event: An HTML event like onclick, mouseover,...
JavaScript Code: JavaScript statements inside quotes.Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline Script Example</title>
</head>
<body>
<button onclick="alert('Hello, welcome to Inline JavaScript!')">Click Me</button>
</body>
</html>Advantages:
It is fast and easy for small scripts
No extra file needed
Disadvantages:
Hard to maintain for large projects
Mixing HTML and JS reduces code readability
Internal Implementation
Internal JavaScript Example
Internal JavaScript means writing JavaScript code inside the <script> tag in the same HTML file. Usually placed inside <head> or <body> sections.
Syntax:
<script>
JavaScript code here
</script>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Internal Script Example</title>
<script>
function wish() {
alert("Hello from Internal JavaScript!");
}
</script>
</head>
<body>
<button onclick="wish()">Click Me</button>
</body>
</html>
You can also place the script tag before closing body tag.
Placing <script> before the closing </body> improves page loading speed because HTML loads before JS.
Advantages:
Keeps JavaScript separate from HTML content
Good for medium-size scripts
Disadvantages:
Still mixes structure (HTML) and behavior (JS) in one file
External Implementation
External JavaScript Example
External JavaScript means writing JavaScript code in a separate .js file and linking it to the HTML file using the <script> tag’s src attribute.
Syntax:
<script src=”example.js”></script>
Example
index.html
<!DOCTYPE html>
<html>
<head>
<title>External Script Example</title>
<script src="script.js"></script>
</head>
<body>
<button onclick="wish()">Click Me</button>
</body>
</html>
script.js
function wish() {
alert("Hello from External JavaScript!");
}Advantages:
JavaScript code is completely separated from HTML → better readability and maintainability
Same
.jsfile can be used in multiple web pages (reusability)Browser caches the
.jsfile → faster loading after first visit
Disadvantages:
Requires an extra HTTP request to load the file (slightly slower initial load)
Comparison among inline, internal, and external
Comparison Table
| Feature | Inline Script | Internal Script | External Script |
|---|---|---|---|
| Location | Inside HTML element | Inside <script> in HTML | Separate .js file |
| Best For | Small code, quick events | Medium scripts | Large, reusable scripts |
| Maintainability | Low | Medium | High |
| Reusability | No | No | Yes |
| Page Speed | Fast for very small code | Medium | Can be cached (fast after first load) |
Comments
In JavaScript, comments are notes written inside the code that the JavaScript engine ignores during execution. They are used to
write description/explain the code
write heading of the program.
hide statements from execution.
There are 3 types of comments
1. Single line comments -- //
2. Multi line comments -- /* */
3. Documentation comments -- /** */
Variables in JavaScript
Introduction
Variables are names of memory allocations those holds data. Think of it a labeled box in a medical store that contains tablets in side the box.
Rules to define variables.
- Can contain letters, digits, underscores,
$. - Cannot start with a digit.
- Case-sensitive (
Nameandnameare different). - Avoid using reserved keywords (e.g.,
var,let,if)
Declaring Variables
In JavaScript there are 3 ways to declare variables.
| Keyword | Scope | Reassignable | Hoisting | Best Use |
|---|---|---|---|---|
var | Function | Yes | Yes | Legacy code |
let | Block | Yes | No | When value changes |
const | Block | No | No | When value should not change |
Examples:
var city = "Nellore"; // Old way
let age = 34; // Modern, preferred
const PI = 3.14159; // Constant value
Datatypes in JavaScript
Datatypes
A datatype specifies which type of value we are using in the program. There are two types of datatypes known as…
- Primitive Types
String → Text (
"Hello",'World')Number → Numeric values (
10,3.14)Boolean → Logical values (
true,false)Undefined → Variable declared but not assigned
Null → Explicitly no value
Symbol → Unique value for object property keys
BigInt → Very large integers
Examples:
let name = "Alice"; // String
let score = 95; // Number
let isPassed = true; // Boolean
let value; // Undefined
let emptyValue = null; // Null
let uniqueID = Symbol(); // Symbol
let bigNumber = 12345678901234567890n; // BigInt
- Non-Primitive Types
Object → Collection of key-value pairs
Array → Ordered list of values
Function → Block of reusable code
Examples:
let student = { name: "Bob", age: 20 }; // Object
let fruits = ["Apple", "Banana", "Cherry"]; // Array
function greet() { console.log("Hello!"); } // Function
Using Console for Debugging
To see output and debug code.
console.log("Hello World!"); // General output
console.warn("Warning!"); // Yellow warning
console.error("Error!"); // Red error
console.table(["HTML", "CSS", "JavaScript"]); // Tabular view
JavaScript Operators & Expressions
What is an operator:
An operator is nothing but a symbol that performs a specific task on a given one or more operands.
Types of Operators in JavaScript
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. String Operators
6. Ternary/Conditional Operator
7. Bitwise Operators
8. Other Operators
Arithmetic Operators
Arithmetic Operators:
Used to perform basic arithmetic operations like addition, subtraction, multiplication... ,
and the operators are ...| 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 |
++ | Increment | x++ | Adds 1 |
-- | Decrement | x-- | Subtracts 1 |
Assignment Operators
Assignment Operators:
Used to assign values to variables.
| Operator | Example | Equivalent to |
|---|---|---|
= |
x = 5 |
x = 5 |
+= |
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 **= 3 |
x = x ** 3 |
Relational / Comparison Operators
Rational/Comparison Operators:
Used to assign values to variables.
| Operator | Example | Equivalent to |
|---|---|---|
= | x = 5 | x = 5 |
+= | 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 **= 3 | x = x ** 3 |
Logical Operators
Logical Operators:
Logical Operators are used to compare more than 2 values or to combine more than 1 relational operators.
These operators return either true or false. And the Operators are...
| Operator | Description | Example | Result |
|---|---|---|---|
&& |
Logical AND | true && false |
false |
|| |
Logical OR | true || false |
true |
! |
Logical NOT | !true |
false |
String Operators
String Operator:
+ is also called concatenation operator that is used to add strings.
for example
'Hello' + 'Suresh'
HelloSuresh
Ternary / Conditional Operator
Ternary Operator: It is a shortcut of an if-else statement. It tests the given condition, if it is true, executes statement1; otherwise, statement2. Syntax: condition ? valueIfTrue : valueIfFalse
Bitwise Operators
Bitwise operators work on numbers at the binary level. JavaScript converts numbers into 32-bit signed integers for bitwise operations, performs the operation, and then converts the result back to a regular JavaScript number.
These operators are often used in low-level programming, optimization, encryption, and graphics programming.
The Bitwise operators are …
| Operator | Symbol | Description | Example |
|---|---|---|---|
| AND | & | Returns 1 only if both bits are 1. | 5 & 3 → 1 |
| OR | ` | ` | Returns 1 if at least one bit is 1. |
| XOR (Exclusive OR) | ^ | Returns 1 if bits are different. | 5 ^ 3 → 6 |
| NOT (Bitwise Negation) | ~ | Inverts bits (turns 0 to 1, 1 to 0). | ~5 → -6 |
| Left Shift | << | Shifts bits to the left, filling with 0. | 5 << 1 → 10 |
| Right Shift (Signed) | >> | Shifts bits to the right, keeping sign bit. | -5 >> 1 → -3 |
| Zero-Fill Right Shift | >>> | Shifts right, filling with 0 (ignores sign). | -5 >>> 1 → 2147483645 |
Examples:
Let’s take two numbers:a = 5 → (0101 in binary)b = 3 → (0011 in binary)
0101 (5) & 0011 (3) = 0001 (1)
console.log(5 & 3); // Output: 1
0101 (5) | 0011 (3) = 0111 (7)
console.log(5 | 3); // Output: 7
0101 (5) ^ 0011 (3) = 0110 (6)
console.log(5 ^ 3); // Output: 6
0101 (5)
~ ----
= 1010 (-6 in decimal, because of 2’s complement)
0101 (5) << 1 = 1010 (10)
console.log(5 << 1); // Output: 10
0101 (5) >> 1 = 0010 (2)
console.log(5 >> 1); // Output: 2
-5 in 32-bit: 11111111111111111111111111111011 >>> 1
= 01111111111111111111111111111101 (2147483645)
Other Operators
typeof Operator:
Thetypeofoperator in JavaScript is used to determine the data type of a given value or variable.
It returns a string that specifies the type.
Syntax: typeof (operand)
Example:
console.log(typeof 42); // "number"
console.log(typeof 3.14); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (special case/quirk in JS)
console.log(typeof [1, 2, 3]); // "object" (arrays are objects)
console.log(typeof {name: "JS"}); // "object"
console.log(typeof function(){}); // "function"
Strings Functions
Introduction
JavaScript provides a rich set of built-in methods to work with strings. A string in JavaScript is a sequence of characters enclosed in single ('), double ("), or backticks (`) for template literals.
String Declaration
You can declare a string in any one of the following way…
- let s1 = ‘Suresh’
- let s2 = “Suresh”
- let s3 =
Suresh`
String Functions
| Method | Description |
|---|---|
| length | Returns the number of characters in the string. |
| charAt(index) | Returns the character at the specified index. |
| charCodeAt(index) | Returns Unicode of the character at the specified index. |
| concat(str1, str2) | Joins two or more strings. |
| includes(substring) | Checks if the string contains the specified substring. |
| startsWith(substring) | Checks if the string starts with the given substring. |
| endsWith(substring) | Checks if the string ends with the given substring. |
Search and Index methhods: |
|
| indexOf(substring) | Returns the first index of the substring, or -1 if not found. |
| lastIndexOf(substring) | Returns the last index of the substring. |
| search(regex) | Searches using regular expression. |
Manipulation Methods |
|
| slice(start, end) | Extracts part of a string from start to end (not including end). |
| substring(start, end) | Similar to slice, but doesn't accept negative values. |
| substr(start, length) | Extracts a substring starting from index with given length. (Deprecated) |
| replace(search, replacement) | Replaces matched substring. |
| replaceAll(search, replacement) | Replaces all matched substrings. |
| split(separator) | Splits the string into an array using separator. |
Case Conversion Methods |
|
| toUpperCase() | Converts the string to uppercase. |
| toLowerCase() | Converts the string to lowercase |
Trim and Pad Methods |
|
| trim() | Removes whitespace from both ends. |
| trimStart() / trimEnd() | Removes whitespace from start/end |
| padStart(length, char) | Pads the string from end. |
Math Functions
What is Math in JavaScript?
In JavaScript, Math is a built-in object that provides a collection of mathematical constants and functions — like rounding numbers, calculating powers, generating random numbers, and working with trigonometry.
Math Constants
| Constant | Description |
|---|---|
| Math.PI | The value of π (3.14159...) |
| Math.E | Euler's number (2.718...) |
| Math.SQRT2 | Square root of 2 |
| Math.SQRT1_2 | Square root of 1/2 |
| Math.LN2 | Natural logarithm of 2 |
| Math.LN10 | Natural logarithm of 10 |
| Math.LOG2E | Base 2 logarithm of E |
| Math.LOG10E | Base 10 logarithm of E |
Functions
| Function | Description |
|---|---|
| Math.round(x) | Rounds x to the nearest integer |
| Math.floor(x) | Rounds x down to nearest integer |
| Math.ceil(x) | Rounds x up to nearest integer |
| Math.trunc(x) | Removes the decimal part (truncates) |
| Math.pow(x, y) | Returns x raised to the power y |
| Math.sqrt(x) | Returns the square root of x |
| Math.cbrt(x) | Returns the cube root of x |
| Math.abs(x) | Absolute (positive) value of x |
| Math.sign(x) | Returns the sign of x (-1, 0, 1) |
| Math.min(x1, x2, ...) | Returns the smallest number |
| Math.max(x1, x2, ...) | Returns the largest number |
| Math.random() | Returns a random number between 0 and 1 |
| Math.log(x) | Natural log (base e) of x |
| Math.log2(x) | Base 2 logarithm of x |
| Math.log10(x) | Base 10 logarithm of x |
| Math.exp(x) | Returns e raised to the power of x |
| Math.sin(x) | Sine of x (in radians) |
| Math.cos(x) | Cosine of x (in radians) |
| Math.tan(x) | Tangent of x (in radians) |
| Math.asin(x) | Arcsine of x |
| Math.acos(x) | Arccosine of x |
| Math.atan(x) | Arctangent of x |
| Math.atan2(y, x) | Arctangent of y/x, considering quadrant |
Arrays in JavaScript
Definition
In JavaScript, an array is a special variable used to store multiple values in a single variable, known as an object.
We can store different data type elements as a single block.
Creating array variables
There are two ways to declare an array variable.
- let numbers = [1,2,3,4,5]
- let number = new Array(5)
for example:
1,2,3,4,5
object
,,,,
Item #3
Strings Methods in JavaScript
Introduction
JavaScript provides a rich set of built-in methods to work with strings. A string in JavaScript is a sequence of characters enclosed in single ('), double ("), or backticks (`) for template literals.
String Declaration
You can declare a string in any one of the following way…
- let s1 = ‘Suresh’
- let s2 = “Suresh”
- let s3 =
Suresh`
String Functions
| Method | Description |
|---|---|
| length | Returns the number of characters in the string. |
| charAt(index) | Returns the character at the specified index. |
| charCodeAt(index) | Returns Unicode of the character at the specified index. |
| concat(str1, str2) | Joins two or more strings. |
| includes(substring) | Checks if the string contains the specified substring. |
| startsWith(substring) | Checks if the string starts with the given substring. |
| endsWith(substring) | Checks if the string ends with the given substring. |
Search and Index methhods: |
|
| indexOf(substring) | Returns the first index of the substring, or -1 if not found. |
| lastIndexOf(substring) | Returns the last index of the substring. |
| search(regex) | Searches using regular expression. |
Manipulation Methods |
|
| slice(start, end) | Extracts part of a string from start to end (not including end). |
| substring(start, end) | Similar to slice, but doesn't accept negative values. |
| substr(start, length) | Extracts a substring starting from index with given length. (Deprecated) |
| replace(search, replacement) | Replaces matched substring. |
| replaceAll(search, replacement) | Replaces all matched substrings. |
| split(separator) | Splits the string into an array using separator. |
Case Conversion Methods |
|
| toUpperCase() | Converts the string to uppercase. |
| toLowerCase() | Converts the string to lowercase |
Trim and Pad Methods |
|
| trim() | Removes whitespace from both ends. |
| trimStart() / trimEnd() | Removes whitespace from start/end |
| padStart(length, char) | Pads the string from end. |
Template Literals & String Interpolation in JavaScript
In JavaScript, working with strings is very common. Traditionally, strings were written using single quotes (‘ ‘) or double quotes (” “). However, these had limitations when:
Adding variables inside strings
Creating multi-line strings
To solve this, Template Literals were introduced in ES6 (ECMAScript 2015).
What are Template Literals?
Template literals are strings enclosed by backticks (
`) instead of single (') or double (") quotes.They provide a more powerful and flexible way to handle strings.
Features of Template Literals
Multi-line Strings:
With normal strings, writing multi-line text required escape characters (\n). Template literals make it easy.
String Interpolation (Embedding Expressions):
The${}syntax allows embedding variables and expressions directly inside a string.
Nesting Template Literals:
You can use template literals inside another template literal.Tagged Templates (Advanced):
A tagged template allows you to parse template literals with a function.
Type Conversion in JavaScript
JavaScript is a loosely typed (or dynamically typed) language, which means variables are not bound to a specific type. The value assigned to a variable determines its type. When working with different data types, JavaScript automatically or manually converts them into other types. This process is called Type Conversion.
There are two types of type conversion in JavaScript:
Implicit Type Conversion (Type Coercion)
Explicit Type Conversion (Type Casting)
Implicit Type Conversion (Type Coercion)
JavaScript automatically converts one data type to another during operations.
Rules of Type Coercion:
If you use
+with a string and a number, the number is converted to a string (concatenation).Other arithmetic operators (
-,*,/,%) convert values to numbers.Boolean values are converted to 1 (true) or 0 (false) when used in arithmetic operations.
Example:
// String + Number → String
let result1 = "10" + 5;
console.log(result1); // "105" (number 5 is coerced into string)
// Number + Boolean → Number
let result2 = 10 + true;
console.log(result2); // 11 (true → 1)
// String * Number → Number
let result3 = "5" * 2;
console.log(result3); // 10 (string "5" → number 5)// String - Number → Number
let result4 = "20" - 5;
console.log(result4); // 15
// String + String → String
let result5 = "Hello " + "World";
console.log(result5); // "Hello World"
Sometimes, implicit conversion may lead to unexpected results:
console.log("5" + 1); // "51" (string concatenation)
console.log("5" - 1); // 4 (string converted to number)Explicit Type Conversion (Type Casting)
Here, developers manually convert values from one type to another using JavaScript methods.
To Number
Number(value)parseInt(value)→ Converts to integerparseFloat(value)→ Converts to floating-point
console.log(Number("123")); // 123
console.log(parseInt("123.45")); // 123
console.log(parseFloat("123.45")); // 123.45
console.log(Number(true)); // 1
console.log(Number(false)); // 0
To String
String(value)value.toString()
console.log(String(100)); // "100"
console.log((100).toString()); // "100"
console.log(String(true)); // "true"
To Boolean
Boolean(value)
Falsy values (converted to false): 0, "", null, undefined, NaN, false
Truthy values (converted to true): All other vlaues.
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("JS")); // true
Comparison: Implicit vs Explicit Conversion
| Feature | Implicit Conversion (Coercion) | Explicit Conversion (Casting) |
|---|---|---|
| Who does it? | JavaScript (automatic) | Developer (manual) |
| Control | Less predictable | Fully controlled |
| Example | "5" + 1 → "51" | Number("5") + 1 → 6 |
| Risk | May lead to unexpected results | Safe and intentional |
Event Handling
What is an event?
An event in JavaScript is an action/occurrence/task that happens in the browser, which the program can respond like…
A user clicks a button (
onclick)A key is pressed (
onkeypress)A web page finishes loading (
onload)A mouse is moved (
onmousemove)
Events can make web pages interactive and dynamic.
What is event handling?
Event Handling refers to the process of capturing events (like clicks, keystrokes, mouse movement) and executing a function (event handler) when the event occurs.
- Event: The action (click, load, keypress, etc.)
- Event Handler: The JavaScript function that runs when the event occurs.
<button onclick=”alert(‘Button Clicked!’)”>Click Me</button>
In the above statement, onclick is an event and alert() is an Event Handler.
Ways to Handle Events in JavaScript
There are several ways to handle events in JavaScript; they are
1. Inline Event Handling (HTML Attribute)
2. Internal Event Handling (Using DOM properties)
3. External Event Handling (Using addEventListener)
Inline Event Handling (HTML Attribute)
You directly attach an event inside the HTML element using event attributes.
Example:
<button onclick="sayWish()">Click Me</button>
<script>
function sayWish() {
alert("Hello! Welcome to Event Handling...");
}
</script>
Internal Event Handling (Using DOM properties)
You assign an event handler to an element’s event property in JavaScript.
Example:
<<button id="myBtn">Click Me</button>
<script>
document.getElementById("myBtn").onclick = function() {
alert("Button was clicked!");
};
</script>
External Event Handling (Using addEventListener)
The most modern and flexible way.
You can attach multiple handlers to a single event.
Keeps HTML and JavaScript separate.
Example:
<<button id="myBtn">Click Me</button>
<script>
let button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Hello! You used addEventListener.");
});
</script>
Common JavaScript Events
| Event | Description |
|---|---|
onclick | Triggered when an element is clicked |
ondblclick | Triggered when an element is double-clicked |
onmouseover | Mouse pointer moves over an element |
onmouseout | Mouse pointer leaves an element |
onmousemove | Mouse moves inside the element |
onkeydown | When a key is pressed down |
onkeyup | When a key is released |
onkeypress | When a key is pressed and released |
onchange | When input value changes (like dropdown/textbox) |
onsubmit | When a form is submitted |
onload | When a web page is fully loaded |
onresize | When browser window is resized |
Event Object
When an event occurs, the browser creates an event object that contains details about the event (e.g., mouse position, key pressed).
<button id="demo">Click Me</button>
<script>
document.getElementById(“demo”).addEventListener(“click”, function(event) {
alert(“You clicked at X: ” + event.clientX + “, Y: ” + event.clientY);
});
</script>
Event Bubbling vs Capturing
What is event bubbling?
Event Bubbling is a mechanism in the DOM where an event starts from the target element (the element that was actually interacted with) and then bubbles up to its parent elements, then to their parents, and so on, until it reaches the document object.
When you click on a child element, the event also gets triggered on its parent(s) unless you stop it.
<div id="parent" style="padding:20px; background:lightblue;">
Parent Div
<button id="child" style="margin:10px;">Click Me</button>
</div>
<script>
document.getElementById("child").addEventListener("click", function() {
alert("Child Button Clicked");
});
document.getElementById("parent").addEventListener("click", function() {
alert("Parent Div Clicked");
});
document.body.addEventListener("click", function() {
alert("Body Clicked");
});
</script>
