--> Sayadasite

Multiple Ads

Search

Menu Bar

Event Handling

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

Event handling in JavaScript refers to the mechanism that allows web pages to react to user interactions or browser actions, known as events. 

An HTML event can be something the browser does, or something a user does.

These events can include actions like clicking a button, hovering over an element, submitting a form, or resizing the browser window. 

Here are some examples of HTML events:

An HTML web page has finished loading

An HTML input field was changed

An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

Here's how event handling works in JavaScript:

1. Events:

An event is a signal that something has occurred in the browser or on the web page. Common events include:

Mouse Events: click, dblclick, mouseover, mouseout, mousemove, mousedown, mouseup.

Keyboard Events: keydown, keyup, keypress.

Form Events: submit, change, focus, blur.

Window Events: load, resize, scroll.

In the following example, an onclick attribute (with code), is added to a <button> element:

Example

<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

Example 2: Alert on Key Press

This example will show how to trigger an alert when a specific key, like the Enter key, is pressed:

// JavaScript code

document.addEventListener('keydown', function(event) {

    if (event.key === 'Enter') {

        alert('Enter key was pressed!');

    }

});

By listening to the keydown event on the entire document, this script checks if the pressed key is the Enter key & displays an alert if true. This can be particularly useful in forms or interactive elements that react to keyboard inputs.

2. Using the ondblclick property (older method):

You can also assign an event handler directly to the ondblclick property of an element.

JavaScript

const myElement = document.getElementById('myButton');

myElement.ondblclick = function() {
  console.log('Element double-clicked!');
};

Example: Mouse Down and Mouse Up Events

The use of the mousedown and mouseup events is exemplified in this scenario: both events apply to a <div> element identified as "mouseUpDownDiv." Two distinct event listeners are established; one responds to the down action of the mouse button, while another reacts upon release or up motion of said button. Upon pressing over the designated div (mousedown), a message indicating that the user has depressed their mouse button appears within your console log. When the user releases the mouse button (mouseup), we also log another message to indicate that the mouse button is up.

<!DOCTYPE html>

<html>

<head>

<title>Mouse Down and Mouse Up Events Example</title>

</head>

<body>

<div id="mouseUpDownDiv" style="width: 600px; height: 100px; background-color: lightblue;"> Please perform mouse down and up event any where in this DIV. </div>

<p id = "output"></p>

<script>

const mouseUpDownDiv = document.getElementById('mouseUpDownDiv');

const outputDiv = document.getElementById("output"); mouseUpDownDiv.addEventListener('mousedown', function(event) {

outputDiv.innerHTML += 'Mouse button down!' +

JSON.stringify(event) + "<br>";

});

mouseUpDownDiv.addEventListener('mouseup', function(event) {

outputDiv.innerHTML += 'Mouse button up!' +

JSON.stringify(event) + "<br>";

});

</script>

 </body>

</html>

 

2. Event Listeners:

Event listeners are functions that "listen" for specific events on a particular element. When the specified event occurs on that element, the event listener triggers a corresponding function, called an event handler.

The primary method for attaching event listeners is addEventListener().

element.addEventListener('event_type', handler_function);

element: The HTML element you want to listen for events on (e.g., a button, a div).

event_type: The type of event to listen for (e.g., 'click', 'mouseover').

handler_function: The function to execute when the event occurs.

Example:

const myButton = document.getElementById('myButton');
function handleClick() {
  alert('Button clicked!');
}
myButton.addEventListener('click', handleClick);

3. Event Handlers:

An event handler is the function that is executed when an event listener detects the specified event. This function contains the logic that defines how the web page should respond to the event. 

4. Event Object:

When an event handler is called, it often receives an Event object as an argument. This object contains useful information about the event, such as:

event.target: The element that triggered the event.

event.type: The type of event that occurred.

event.preventDefault(): A method to prevent the default action of an event (e.g., preventing a form submission).

event.stopPropagation(): A method to stop the event from bubbling up to parent elements.

Example with Event Object:

const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevents the default form submission
  console.log('Form submitted!');
});

Alternative Methods (less recommended for modern development):

Inline HTML Event Handlers: 

Directly embedding JavaScript code within HTML attributes (e.g., <button onclick="alert('Clicked!')">). This is generally discouraged for larger projects due to separation of concerns and maintainability issues.

DOM Level 0 Handlers: 

Assigning a function directly to an element's event property (e.g., myButton.onclick = handleClick;). This method only allows one handler per event type per element.

By using event handling, developers can create interactive and dynamic web applications that respond effectively to user input and browser actions.

 

 

Date and math related objects

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

The JavaScript Math object is a built-in, global object that provides properties and methods for performing mathematical operations. 

The JavaScript Math object allows you to perform mathematical tasks.

The Math object is static.

All methods and properties can be used without creating a Math object first.

It is not a constructor function, meaning you cannot create new instances of Math using the new keyword. 

All of its properties and methods are static and can be accessed directly using Math.propertyName or Math.methodName(). 

Key Characteristics:

Static: All properties and methods are static and accessed directly on the Math object (e.g., Math.PI, Math.random()).

Not a constructor: You cannot create Math objects using new Math().

Works with Number type: Math operations are designed for JavaScript's Number type and do not work with BigInt.

Commonly Used Properties:

The Math object in JavaScript provides a clear distinction between its properties and methods, though both are accessed statically.

Definition: 

Properties are named values associated with an object. In the context of the Math object, these are typically mathematical constants.

Purpose: 

They represent fixed, unchangeable values that are commonly used in mathematical calculations.

Characteristics:

They are static, meaning they are accessed directly on the Math object itself (e.g., Math.PI).

They do not perform any actions; they simply provide a value.

Examples

Math.PI: Represents the ratio of a circle's circumference to its diameter, approximately 3.14159.

Math.E: Represents Euler's number, the base of natural logarithms, approximately 2.718.

Math.LN2: Represents the natural logarithm of 2.

Math.LN10: Represents the natural logarithm of 10.

Commonly Used Methods:

Definition: 

Methods are functions associated with an object. In the case of the Math object, these are functions that perform specific mathematical operations.

Purpose: 

They allow you to perform calculations and manipulations on numbers.

Characteristics:

They are static, meaning they are called directly on the Math object (e.g., Math.sqrt(x)).

They perform an action and typically return a result.

Examples

Math.abs(x): Returns the absolute value of x.

Math.ceil(x): Rounds x upwards to the nearest integer.

Math.floor(x): Rounds x downwards to the nearest integer.

Math.round(x): Rounds x to the nearest integer.

Math.trunc(x): Returns the integer part of x by removing any fractional digits.

Math.max(x, y, ...): Returns the largest of zero or more numbers.

Math.min(x, y, ...): Returns the smallest of zero or more numbers.

Math.pow(x, y): Returns x raised to the power of y.

Math.sqrt(x): Returns the square root of x.

Math.random(): Returns a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive).

Math.sin(x), Math.cos(x), Math.tan(x): Trigonometric functions (input in radians).

Math.log(x): Returns the natural logarithm (base e) of x.

Example:

let radius = 5;
let area = Math.PI * Math.pow(radius, 2); // Calculate the area of a circle
console.log(area); // Output: 78.53981633974483

let randomNumber = Math.random(); // Generate a random number between 0 and 1
console.log(randomNumber);

let roundedNumber = Math.round(4.7); // Round to the nearest integer
console.log(roundedNumber); // Output: 5

Document object model

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

The W3C DOM standard is separated into 3 different parts:

Core DOM - standard model for all document types

XML DOM - standard model for XML documents

HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:

The HTML elements as objects

The properties of all HTML elements

The methods to access all HTML elements

The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page's structure as a logical tree, where each part of the document (elements, attributes, text) is represented as a node object. JavaScript interacts with this DOM to dynamically manipulate the content, structure, and style of a web page. 

Key aspects of the DOM in JavaScript:

Tree Structure: 

The DOM organizes the document as a hierarchical tree of objects. The document object is the root, and all other elements are its descendants.

Node Types: 

Various types of nodes exist in the DOM tree, including:

Element nodes: Represent HTML tags (e.g., <div>, <p>, <a>).

Text nodes: Represent the text content within elements.

Attribute nodes: Represent attributes of elements (e.g., href in <a>).

Comment nodes: Represent HTML comments.

Accessing Elements: 

JavaScript provides methods to select and access specific elements in the DOM:

document.getElementById(): Selects an element by its unique ID.

document.getElementsByClassName(): Returns a collection of elements with a specific class name. 

document.getElementsByTagName(): Returns a collection of elements with a specific tag name.

document.querySelector(): Returns the first element that matches a CSS selector.

document.querySelectorAll(): Returns all elements that match a CSS selector.

Example

The following example changes the content (the innerHTML) of the <p> element with id="demo":

Example

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

</body>
</html>

The getElementById Method

The most common way to access an HTML element is to use the id of the element.

In the example above the getElementById method used id="demo" to find the element.

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The innerHTML property is useful for getting or replacing the content of HTML elements.

The innerHTML property can be used to get or change any HTML element, including <html> and <body>.

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

 

Manipulating Elements: 

Once elements are accessed, their content, attributes, and styles can be modified:

element.textContent or element.innerHTML: To change the text or HTML content of an element.

element.setAttribute(): To add or modify an attribute.

element.style.propertyName: To change inline CSS styles.

Creating and Removing Elements: 

New elements can be created and added to the document, and existing elements can be removed:

document.createElement(): Creates a new element node.

document.createTextNode(): Creates a new text node.

parentNode.appendChild(): Appends a child node to a parent.

parentNode.removeChild(): Removes a child node from a parent.

Types of Functions

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

Main Types of functions in JavaScript:

1. Named Function

A function that has its own name when declared. It’s easy to reuse and debug because the name shows up in error messages or stack traces.

function greet() {

  return "Hello!";

}

console.log(greet()); // Hello!

2. Anonymous Function

A function that does not have a name. It is usually assigned to a variable or used as a callback. Since it has no name, it cannot be called directly.

const greet = function() {

  return "Hi there!";

};

console.log(greet()); // Hi there!

3. Function Expression

When you assign a function (can be named or anonymous) to a variable. The function can then be used by calling that variable.

const add = function(a, b) {

  return a + b;

};

console.log(add(2, 3)); // 5

4. Arrow Function (ES6)

A new way to write functions using the => syntax. They are shorter and do not have their own this binding, which makes them useful in some cases.

const square = n => n * n;

console.log(square(4)); // 16

Arrow Functions

Arrow functions were introduced in ES6.(also known as ECMAScript 2015)

Arrow functions allow us to write shorter function syntax:

Before Arrow:

Function to compute the product of a and b

let myFunction = function(a, b) {return a * b}
With Arrow

let myFunction = (a, b) => a * b;

Learn More:

JavaScript Arrow Functions

5. Immediately Invoked Function Expression (IIFE)

IIFE functions are executed immediately after their definition. They are often used to create isolated scopes.

 (function () {

    console.log("This runs immediately!");

})();

6. Callback Functions

A callback function is passed as an argument to another function and is executed after the completion of that function.

function num(n, callback) {

    return callback(n);

}

const double = (n) => n * 2;

console.log(num(5, double));

 

7. Constructor Function

A special type of function used to create multiple objects with the same structure. It’s called with the new keyword.

function Person(name, age) {

  this.name = name;

  this.age = age;

}

const user = new Person("Neha", 22);

console.log(user.name); // Neha

8. Async Function

Functions that handle asynchronous tasks. Declared with async, they return a Promise, and you can use await inside them to pause until another Promise resolves.

async function fetchData() {

  return "Data fetched!";

}

fetchData().then(console.log); // Data fetched!

9. Generator Function

Declared with an asterisk *, these functions can pause execution using yield and resume later. Useful for lazy loading values or handling iterators.

function* numbers() {

  yield 1;

  yield 2;

  yield 3;

}

​const gen = numbers();

console.log(gen.next().value); // 1

console.log(gen.next().value); // 2

10. Recursive Function

A function that calls itself until a condition is met. Very useful for problems like factorial, Fibonacci, or tree traversals.

function factorial(n) {

  if (n === 0) return 1;

  return n * factorial(n - 1);

}

console.log(factorial(5)); // 120

11. Higher-Order Function

A function that either takes another function as a parameter or returns another function. These are common in JavaScript (e.g., map, filter, reduce).

function multiplyBy(factor) {

  return function(num) {

    return num * factor;

  };

}

​const double = multiplyBy(2);

console.log(double(5)); // 10

12. Nested Functions

Functions defined within other functions are called nested functions. They have access to the variables of their parent function.

function outerFun(a) {

    function innerFun(b) {

        return a + b;

    }

    return innerFun;

}

const addTen = outerFun(10);

console.log(addTen(5));

13. Pure Functions

Pure functions return the same output for the same inputs and do not produce side effects. They do not modify state outside their scope, such as modifying global variables, changing the state of objects passed as arguments, or performing I/O operations.

function pureAdd(a, b) {

    return a + b;

}

​console.log(pureAdd(2, 3));

14. Default Parameter Function

A function where parameters have default values if no argument is passed. Helps avoid undefined issues.

function greet(name = "Guest") {

  return "Hello, " + name;

}

console.log(greet());      // Hello, Guest

console.log(greet("Aman"));// Hello, Aman

15. Rest Parameter Function

Uses ... to collect all remaining arguments into an array. Very useful when you don’t know how many arguments will be passed.

function sum(...nums) {

  return nums.reduce((a, b) => a + b, 0);

}

console.log(sum(1, 2, 3, 4)); // 10

Functions in JavaScript

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

What are Functions?

Functions are fundamental building blocks in all programming language.

Functions are reusable block of code designed to perform a particular task.

Functions are executed when they are "called" or "invoked".

They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs

Example

Function to compute the product of two numbers:

function myFunction(p1, p2) {
  return p1 * p2;
}
JavaScript Function Syntax

function name( p1, p2, ... ) {
  // code to be executed
}

Functions are defined with the function keyword:

followed by the function name

followed by parentheses ( )

followed by brackets { }

The function name follows the naming rules for variables.

Optional parameters are listed inside parentheses: ( p1, p2, ... )

Code to be executed is listed inside curly brackets: { }

Functions can return an optional value back to the caller.

Why Functions?

Functions enable better code organization and efficiency.

With functions you can reuse code.

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

Function Invocation ()

The code inside the function will execute when "something" invokes (calls) the function:

When it is invoked (called) from JavaScript code

When an event occurs (a user clicks a button)

Automatically (self invoked)

The () operator invokes a the function.

Example

toCelsius() invokes the toCelsius function:

// Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}
// Call the toCelcius() function
let value = toCelsius(77);

Accessing a function with incorrect parameters can return an incorrect answer:

Example

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}

let value = toCelsius();

Accessing a function without (), returns the function itself and not the result:

Example

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}
let value = toCelsius;

Note

In the examples above:

toCelsius refers to the function object.

toCelsius() refers to the function result.

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Example

// code here can NOT use carName
function myFunction() {
  let carName = "Volvo";
  // code here CAN use carName
}
// code here can NOT use carName

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Understanding Functions

In functions, parameters are placeholders defined in the function, while arguments are the actual values you pass when calling the function

Example:

function greet(name) {   // 'name' is a parameter

  console.log("Hello " + name);

}

​greet("Ali");  // "Ali" is the argument

Parameter → name (placeholder inside the function).

Argument → "Ali" (real value given at call time).

Default Parameters

Default parameters are used when no argument is provided during the function call.

If no value is passed, the function automatically uses the default value.

function greet(name = "Guest") {

  console.log("Hello, " + name);

}

​greet();        // Hello, Guest (default used)

greet("Aman");  // Hello, Aman

Return Statement

The return statement is used to send a result back from a function.

When return executes, the function stops running at that point.

The returned value can be stored in a variable or used directly.

function add(a, b) {

  return a + b; // returns the sum

}

​let result = add(5, 10);

console.log(result); // 15

Parameters vs. Arguments

In JavaScript, function parameters and arguments are distinct concepts:

Parameters are the names listed in the function definition.

Parameters are the names of the values that will be passed.

Example

"name" and "age" are parameters:

function greet(name, age) {
  return `Hello $name! You are ${age} years old.`;
}

The name and age variables are embedded (fix) directly into the string using ${variableName} syntax.

Arguments are the values passed to the function when it is invoked or called.

Arguments are the values received by the function.

Example

"John" and 21 are arguments:

greet("John", 21);

Functions Used as Variables

Functions can be used as variables, in all types of formulas, assignments, and calculations.

Example

Instead of using a variable to store the return value of a function:

let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";

 

Expressions and statements

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

In JavaScript, the distinction between expressions and statements is fundamental to understanding how code executes.

Expressions:

An expression is any piece of code that evaluates to a single value. Expressions can be simple or complex, and they always produce a result. 

Examples of Expressions:

Literals: 5, "hello", true

Variables: x, myVariable

Arithmetic operations: 

2 + 3, x * y

String concatenation: 

"Hello" + " World"

Function calls: 

myFunction(), console.log("message")

Logical operations: 

a && b, !c

Assignment expressions: x = 10 (the expression itself evaluates to the assigned value, 10)

Key characteristics of expressions:

Always produce a value: This is the defining feature of an expression.

Can be simple or complex: They can be a single literal or a complex combination of operators, variables, and function calls.

Can be nested: Expressions can contain other expressions, allowing for complex computations.

Statements:

A statement is a complete instruction that performs an action or controls the flow of execution in a program. Statements do not necessarily evaluate to a value, although they often contain expressions.

Examples of Statements:

Variable declarations: 

let x;, const PI = 3.14;

Conditional statements: 

if (condition) { ... } else { ... }

Loop statements: 

for (let i = 0; i < 5; i++) { ... }, while (condition) { ... }

Function declarations: 

function greet() { ... }

Block statements: 

{ console.log("inside block"); }

Expression statements: 

An expression followed by a semicolon, like x = 5; or myFunction();

Key Differences:

Value Production: Expressions always produce a value, while statements perform an action.

Usage: Expressions can be used wherever a value is expected (e.g., as arguments to functions, in assignments, within other expressions). Statements form the core instructions of a program.

Context in Frameworks: In contexts like React's JSX, only expressions are permitted within curly braces {} for dynamic content, not statements. (What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React, React lets you build user interfaces out of individual pieces called components. Create your own React components like Thumbnail, LikeButton, and Video.)

Relationship:

Expressions are often components of statements. For instance, in if (x > 5) { ... }, x > 5 is an expression that evaluates to a boolean value, and the entire if construct is a statement. Similarly, let result = a + b; involves the expression a + b within a variable declaration statement.

JavaScript Statements

Example

let x, y, z;    // Statement 1
x = 5;          // Statement 2
y = 6;          // Statement 3
z = x + y;      // Statement 4
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";

 

Semicolons ;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

Examples

let a, b, c;  // Declare 3 variables
a = 5;        // Assign the value 5 to a
b = 6;        // Assign the value 6 to b
c = a + b;    // Assign the sum of a and b to c

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;

JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Keyword

Description

var

Declares a variable

let

Declares a block variable

const

Declares a block constant

if

Marks a block of statements to be executed on a condition

switch

Marks a block of statements to be executed in different cases

for

Marks a block of statements to be executed in a loop

function

Declares a function

return

Exits a function

try

Implements error handling to a block of statements

Note

JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.