JavaScript Functions & Objects Guide
JavaScript Functions & Objects Guide
(Elective- III)
Javascript
- Complete Notes -
For End-Sem Examination
( Covered All the previous year Question and some
expected question )
DESIGNED BY
Professors At Top Ranked Institute In SPPU
Unit-3: Functions & Objects
Expected Questions :
-> What is function? Explain with example how to pass and return parameters
and arguments from called function to the calling function.
-> What are Common properties and methods of object in JavaScript?
-> Write a JavaScript program to pass the function by reference, perform
addition of two objects inside the function and display the result in calling
function.
-> What is Anonymous Functions in JavaScript? Explain its use with an example.
-> Write a JavaScript program that will append an object to an array and will
check if an object is an array data types.
-> Explain data types in JavaScript? Differentiate between primitive and non-
primitive.
-> Explain the Mask out with respect to functions in Java Script.
-> Explain how function is used as object in Java Script.
-> How Arrays can be used as Stacks and Queues in Java Script.
-> Explain different types of Objects.
-> List the various methods of Math object. Explain any one with example.
Expected Question :
-> a) What is function? Explain with example how to pass and return
parameters and arguments from called function to the calling function
Functions
- Functions in JavaScript are reusable code blocks used to perform specific
tasks multiple times.
- Functions should ideally be self-contained, with clear input (parameters) and
output.
- JavaScript allows modular code through functions and supports advanced
features like variable parameter lists.
- Function names should follow the same rules as variable names, and descriptive
names are recommended to reflect the function’s purpose.
function functionName(parameter-list) {
// statements
}
Calling a Function
- A function must be defined before calling it unless it is defined in a ‘<script>‘
tag, where forward references can be made.
Parameter Passing
- Parameters are data sent to a function to perform operations, while arguments
are the values provided when the function is called.
- JavaScript does not require a data type while defining parameters.
- If a parameter is defined without an argument being passed, its value will be
‘undefined’.
- Example of a simple function with a parameter:
function sayHello(name) {
if (name != "")
alert("Hello " + name);
else
alert("Don't be shy");
}
sayHello("George"); // This will show: Hello George
- Here, the function modifies ‘arg1’ but does not affect the original value of ‘x’
since it works with a copy.
- Here, the original array ‘x’ is modified because the function operates on its
reference.
- Example:
function addThree(arg1, arg2, arg3) {
return arg1 + arg2 + arg3;
}
var x = 5, y = 7;
var result = addThree(x, y, 11); // result = 23
- If no ‘return’ statement is included, the function returns ‘undefined’ by default.
Global Variables
- Global variables are defined outside functions and are accessible throughout
the document.
- Multiple functions can access and modify global variables.
- Example:
var x = 5; // Global variable
function myFunction() {
[Link]("Entering function<br>");
[Link]("x = " + x + "<br>"); // x = 5
x = 7; // Modify global variable
[Link]("x = " + x + "<br>"); // x = 7
[Link]("Leaving function<br>");
}
[Link]("Starting Script<br>");
[Link]("x = " + x + "<br>"); // x = 5
myFunction();
[Link]("x = " + x + "<br>"); // x = 7
[Link]("Ending Script<br>");
- Modifying a global variable within a function changes its value for the entire
script.
- Global variables reduce reusability and increase complexity in scripts.
- Variables declared without the ‘var’, ‘let’, or ‘const’ keyword automatically
become global.
- Example:
function greet() {
a = "hello"; // ‘a’ becomes global
}
greet();
[Link](a); // hello
- Avoid using global variables wherever possible to maintain code reusability and
simplicity.
Local Variables
- A local variable is one that is defined within a specific block of code and can
only be accessed within that block.
- The scope of a local variable is restricted to the block of code (denoted by ‘{}’)
in which it is declared.
- Local variables are created to encapsulate functionality and hide the
implementation details of a function.
- Example:
function myFunction() {
var y = 5; // local variable
[Link]("Within function, y = " + y + "<br>");
}
myFunction();
[Link]("After function, y = " + y + "<br>"); // undefined
- In this example, the variable ‘y’ is only accessible within ‘myFunction’. Outside
of the function, trying to access ‘y’ results in ‘undefined’.
- Local variables help in creating functions that can be reused without exposing
their internal implementation.
Expected Question :
a) Explain the Mask out with respect to functions in Java Script.
Mask Out :
- When both local and global variables have the same name, the local variable
takes precedence over the global one inside the function. This is known as "mask
out".
- Example:
var x = "As global I am a string"; // Global variable
function maskDemo() {
var x = 5; // Local variable with the same name as global variable
[Link]("In function, x = " + x + "<br>"); // 5
}
[Link]("Before function call, x = " + x + "<br>"); // As global I am a
string
maskDemo();
[Link]("After function call, x = " + x + "<br>"); // As global I am a string
- Here, the local variable ‘x’ inside ‘maskDemo’ "masks out" the global ‘x’ within
the function, and the value of global ‘x’ remains unchanged after the function
call.
- To avoid confusion and conflicts, it’s a good practice to use unique variable
names, especially when reusing scripts.
Local Functions
- A local function is defined inside another function. These functions are also
known as inner functions or nested functions.
- Functions in JavaScript are treated as objects, and this allows them to be
defined within other functions.
- Local functions can only be called within the function in which they are
declared.
- Example:
function testFunction() {
function inner1() {
[Link]("testFunction-inner1 <br>");
}
function inner2() {
[Link]("testFunction-inner2 <br>");
}
[Link]("Entering testFunction <br>");
inner1();
[Link]("Leaving testFunction <br>");
inner2();
}
[Link]("About to call testFunction <br>");
testFunction();
- In this example, the functions ‘inner1’ and ‘inner2’ are defined inside
‘testFunction’ and can only be called within ‘testFunction’.
- Attempting to call ‘inner1()’ or ‘inner2()’ outside of ‘testFunction’ will result in
an error.
- Local functions provide a way to organize code into self-contained blocks,
allowing for modular development.
- Local or nested functions have been supported in browsers since the 4.x
generation.
Expected Question :
b) Explain how function is used as object in Java Script.
Functions as Objects
- In JavaScript, functions are treated as objects.
- This means that, like other objects, functions can be assigned to variables,
passed as arguments, and returned from other functions.
- Functions can also be created using the ‘Function’ constructor.
Syntax
var functionName = new Function("argument1", "argument2", "body of function");
Reusing Functions
Functions can be assigned to other variables, allowing them to be reused or called
with different names.
var sayHelloAgain = sayHello;
sayHelloAgain();
- The key advantage of using the ‘Function()’ constructor is that it allows the
creation of functions dynamically, even after the page is loaded.
Expected Question :
a) What is Anonymous Functions in JavaScript? Explain its use with an
example.
Syntax
var variablename = function(argumentList) {
// Function body
};
- In this case, the function does not have a name, but it can be assigned to a
variable or passed as an argument.
Arrow Functions
- Arrow functions, introduced in ES6, offer a more concise syntax for writing
functions.
- They use the ‘=>‘ syntax and do not require the ‘function’ keyword. However,
arrow functions have some differences compared to traditional functions:
- They do not have their own ‘this’ context, but inherit it from the surrounding
code.
- They cannot be used as constructors (i.e., with the ‘new’ keyword).
- They are always anonymous.
- Arrow functions provide a more concise way to write functions, especially when
they are used as callbacks or in simple operations.
Static Variables :
- In JavaScript, we can create static variables within a function.
- These are variables that persist across function invocations, meaning their
value is retained between calls.
- Static variables are typically created by adding an instance property to the
function.
- The value of a static variable is shared across all invocations of the function,
and it doesn't get reinitialized each time the function is called.
function doSum(x, y) {
[Link] = [Link] || 0; // Define a static variable
[Link] += (x + y); // Update running sum
return [Link]; // Return the current sum
}
[Link]("First Call: " + doSum(5, 10) + "<br />"); // 15
[Link]("Second Call: " + doSum(5, 10) + "<br />"); // 38
[Link]("Third Call: " + doSum(100, 100) + "<br />"); // 230
Output:
Number of parameters defined: 0
Number of parameters passed: 3
Parameter 1: 33
Parameter 2: 858
Parameter 3: 404
- In this example, even though the function doesn't define any parameters, the
‘arguments[]’ array captures the passed arguments.
alert(sumAll(3, 5, 3, 5, 3, 2, 6)); // 27
- In this example, ‘sumAll’ adds all the numbers passed to it, regardless of how
many parameters are provided.
- This function works best when only numbers are passed; passing strings would
lead to unexpected results.
- By using the ‘arguments[]’ array, we can handle a flexible number of parameters
without needing to predefine them.
Recursive Functions
- A recursive function is a function that calls itself in order to solve a problem.
- This approach is often used when a problem can be divided into smaller
subproblems of the same type.
- While recursion can lead to elegant solutions, it may not always be the most
efficient, especially in terms of execution time due to the overhead of repeated
function calls.
Factorial Example
- A common example of recursion is calculating the factorial of a number,
defined mathematically as:
- ‘factorial(n) = n * (n - 1) * (n - 2) * ... * 1’
- ‘factorial(0) = 1’
function factorial(n) {
if (n === 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
alert(factorial(5)); // 120
- In this example, the function ‘factorial’ keeps calling itself with smaller values
of ‘n’ until it reaches the base case (‘n === 0’).
- If a negative value is passed, the function would result in a Stack Overflow
error due to the infinite recursion.
var x = 5; // Variable
function x() { // Function
alert("I'm a function!");
}
alert(typeof x); // number
- In this case, there could be confusion, as the variable ‘x’ might override the
function ‘x’.
function noReturn() {
alert("This function does not return anything.");
return; // Explicit return
}
For example:
function calculateSum(a, b) {
return a + b; // Stand-alone function
}
- By following these practices, your code will be more maintainable, modular, and
less prone to bugs.
function addTwoNumbers(x, y) {
alert(x + y);
}
addTwoNumbers(5); // Undefined behavior
function addTwo(x, y) {
if ([Link] == 2) {
alert(x + y);
} else {
alert("Two arguments are required.");
}
}
- In this revised version, the function checks if exactly two arguments were
provided before performing the addition.
- If fewer arguments are passed, it will show a message indicating that two
arguments are needed.
For example:
function addTwo(x, y) {
if ([Link] == 2) {
if (typeof(x) !== "number" || typeof(y) !== "number") {
alert("Both arguments must be numbers.");
return;
}
alert(x + y);
} else {
alert("Two arguments are required.");
}
}
- Here, the function checks both the number of arguments and their types,
ensuring that both ‘x’ and ‘y’ are numbers before performing the addition.
Comment Functions
- Good programming practices involve documenting your functions to describe
their purpose, inputs, outputs, and any side effects.
- A well-commented function helps other developers (or even yourself)
understand the code easily.
/*
Function: customAlert
Description: Creates a custom alert dialog with a message, icon, background
color, and button text.
Input:
- message: A string containing the message to be displayed.
- icon: Reference to a GIF or JPEG image to be used in the dialog.
- color: The background color in hexadecimal. Defaults to white if unspecified.
- buttontext: The text for the button. Defaults to "ok" if unspecified.
Output: Creates a dialog window and returns true if successful, false otherwise.
*/
- Such comments improve the maintainability of your code and ensure that other
developers can easily use or modify the function.
Objects in JavaScript
Expected Question :
1) Explain different types of Objects.
Types of Objects
- Objects in JavaScript fall into four main categories:
1. User-defined Objects
- These are objects created by the programmer to bring structure and
consistency to a particular task. They can be created in three ways:
Object Literal
This is the simplest way to create an object by directly defining properties
and values.
var emp = {
id: 102,
name: "Sunil Kumar",
salary: 40000
};
Data Type Objects: ‘String’, ‘Number’, and ‘Boolean’ which encapsulate primitive
data types.
Composite Objects: ‘Object’ and ‘Array’ used for more complex data structures.
Utility Objects: ‘Date’, ‘Math’, and ‘RegExp’ are built to simplify common tasks
like handling dates, performing mathematical calculations, and working with
regular expressions.
- Each built-in object comes with predefined methods and properties that
simplify programming.
3. Browser Objects
- These objects are not part of JavaScript itself but are typically supported by
most browsers. Examples include:
- Browser objects are not standardized and their behavior might differ across
different browsers and versions.
Garbage Collection
- Garbage collection is the process by which JavaScript automatically manages
memory.
- When an object or variable is no longer accessible (for instance, when it goes
out of scope), the JavaScript engine marks that object as eligible for garbage
collection, which means the memory occupied by that object will be returned to
the pool of available memory for future use.
- This feature prevents memory leaks and ensures efficient memory usage
without manual intervention.
Example:
obj = null; // Now the object is eligible for garbage collection because it's no
longer referenced
- JavaScript automatically takes care of cleaning up the memory when objects
are no longer needed.
Syntax:
Example:
var person = {
firstName: "John",
lastName: "Doe",
age: 25
};
for (let prop in person) {
[Link]("Property: " + prop + ", Value: " + person[prop]);
}
- Primitive types: These include ‘number’, ‘string’, ‘boolean’, ‘undefined’, and ‘null’.
They hold the actual value directly.
- Reference types: These include objects, arrays, and functions. Instead of
holding the actual value, a reference type variable holds a reference to the
memory location where the actual data is stored.
- In the above example, since ‘x’ is a primitive type (‘number’), when ‘y’ is assigned
‘x’, a copy of ‘x’'s value is made. Changing the value of ‘x’ later doesn't affect ‘y’.
- In this case, both ‘x’ and ‘y’ point to the same array in memory.
- Modifying the array through either variable will be reflected in the other,
since they both reference the same object.
Passing Objects to Functions in JavaScript
- In JavaScript, we can pass objects to functions just like other data types.
- However, there are important differences between how primitive types and
reference types behave when passed to functions.
Passing Objects:
- Objects, on the other hand, are reference types. When you pass an object to
a function, a reference to the original object is passed.
- This means that the function can modify the original object because both the
original and the copy point to the same memory location.
Example:
Explanation:
- The ’refType’ array is a reference type, so when it's passed to the function,
both the original variable and the function's parameter point to the same array
in memory.
- Therefore, modifying the array inside the function changes the original
‘refType’ variable.
- The ’primType’ is a primitive type, so only a copy of the value is passed to the
function. Modifying ‘prim’ inside the function does not affect the original
‘primType’ variable.
Expected Question :
b) What are Common properties and methods of object in JavaScript?
- All JavaScript objects share some common properties and methods. These help
when working with objects, both built-in and custom.
Common Properties and Methods :
1. prototype
- This property points to the object from which the object inherits non-
instance properties.
2. constructor
- This refers to the function that created the object.
3. toString()
- Converts the object into a string, with behavior depending on the object.
4. toLocaleString()
- Converts the object into a localized string (depending on locale).
5. valueOf()
- Converts the object into a primitive type, usually a number.
6. hasOwnProperty(prop)
- Returns ‘true’ if the object has the specified property.
7. isPrototypeOf(obj)
- Returns ‘true’ if the object is the prototype of another object.
8. propertyIsEnumerable(prop)
- Returns ‘true’ if the specified property will show up in a ‘for/in’ loop.
Prototype-Based Inheritance
- In JavaScript, objects are prototype-based. This means that each object has
a prototype, which is an object it inherits properties and methods from.
- Every object in JavaScript has a prototype. This prototype is another object
that contains shared data and methods.
- If an object does not have a property, JavaScript will look for that property
in the object's prototype.
[Link] = "Indian";
- You can also add new methods to objects by modifying their prototype. For
example, adding a ‘display()’ method to the ‘Person’ object:
[Link] = function() {
return [Link] + " " + [Link];
};
By using prototypes, you can modify objects even after they have been created,
allowing you to extend their functionality as needed.
Constructor in JavaScript
- In JavaScript, object instances are created using constructors.
- A constructor is a special function that prepares new instances of an object
for use.
- When you use a constructor, it is called in conjunction with the new operator.
- JavaScript knows that these functions are constructors because they are
invoked using new.
- It is a common practice to start constructor names with an uppercase letter,
distinguishing them from instance variables, which start with a lowercase letter.
- When the constructor is invoked, JavaScript automatically allocates memory
for the new object and passes a reference to the object within the constructor
using the this keyword.
Constructor Example:
toString() Method
- The ‘toString()’ method converts an object into a string representation.
- It is automatically invoked when an object is used in a context that requires a
string.
Syntax:
[Link](radix)
- Here, ‘radix’ is optional and can take values between 2 and 36 (e.g., 2 for binary,
8 for octal).
Example:
let num = 15;
let text = [Link](2); // converts to binary string
[Link](typeof(text)); // string
valueOf() Method
- The ‘valueOf()’ method is used to convert an object to its most appropriate
primitive value, usually a number. It doesn't change the original object.
Example:
var n1 = "1234";
var n2 = [Link]();
[Link](n2); // 1234 (as number)
hasOwnProperty() Method
- The ‘hasOwnProperty()’ method checks if an object has a specific property. It
returns ‘true’ if the property exists on the object itself and not its prototype.
Example:
var movie = {
name: 'Iron Man',
genre: 'Super Hit'
};
[Link]([Link]('name')); // true
[Link]([Link]('type')); // false
- This method ignores inherited properties, making it useful for checking only
the object's own properties.
isPrototypeOf() Method
- The ‘isPrototypeOf()’ method checks if an object is part of another object's
prototype chain.
- It returns ‘true’ if the object exists in the prototype chain of another object.
Example:
class Foo {}
class Bar extends Foo {}
class Baz extends Bar {}
[Link]([Link](baz)); // true
[Link]([Link](bar)); // false
- The method checks the prototype chain of the object and determines if the
prototype object is part of it.
Generic and User-Defined Objects in JavaScript
- In JavaScript, generic objects can be used to create user-defined data types,
which are one of the most powerful tools for writing complex scripts.
- These generic objects can be created using object literals or the object
constructor.
- As with any JavaScript object, properties and methods can be added
dynamically.
For example:
- In this example, an object ‘robot’ is created, and various properties (like ‘name’,
‘model’, ‘hasJetpack’) and a method ‘attack’ are added to it.
- This illustrates one of the most common uses of generic objects: grouping
related data and functions together.
Object Literals
- JavaScript also supports object literals, which is a more compact way to create
objects.
- Object literals are commonly used because they simplify the process of
defining objects with properties and methods.
- The syntax for an object literal is to use curly braces ‘{}’, and inside the braces,
you list property/value pairs separated by commas.
- Each property name is followed by a colon ‘:’ and its corresponding value.
Syntax:
var myObject = {
property1: 'value1',
property2: 'value2',
method1: function() {
// method body
},
method2: function() {
// method body
}
};
var robot = {
name: "Zephyr",
model: "Guard",
hasJetpack: true,
attack: function() {
alert("ZAP!");
}
};
- This example creates the same ‘robot’ object using object literal syntax.
- The object has properties such as ‘name’, ‘model’, and ‘hasJetpack’, and a
method ‘attack’ that triggers an alert.
- You can also use nested objects and properties with null or undefined values in
object literals, which gives you great flexibility when defining complex objects.
Array in JavaScript
Expected Question :
1) How Arrays can be used as Stacks and Queues in Java Script.
Declaring Arrays
Arrays can be declared in different ways:
1. Using Array Literal:
var myArray = [2, 4, 6, 8, "ten"];
4. Empty Array:
var myArray = [];
Expected Question :
1) Write a JavaScript program that will append an object to an array and
will check if an object is an array data types.
Array Methods
- JavaScript arrays have many built-in methods to perform operations on them.
Here are some commonly used array methods:
- ’find()’: Returns the first element in the array that satisfies a specified
condition.
var arr = [5, 10, 15];
var found = [Link](num => num > 8); // 10
- ’pop()’: Removes the last element from an array and returns that element.
var arr = [2, 4, 6];
var last = [Link](); // 6
1. Using ‘push()’:
var arr = [2, 4, 6, 8];
var obj = {x: 5, y: "ten"};
[Link](obj);
2. Using ‘splice()’:
Date Constructors
- JavaScript provides several ways to create Date objects:
1. No arguments:
- If no arguments are passed, it creates a Date object representing the current
date and time.
var currentDate = new Date();
4. Multiple arguments:
- You can pass a year, month, day, hours, minutes, seconds, and milliseconds.
var d = new Date(2021, 3, 27, 15, 55, 30, 0);
// Output: Tue Apr 27 2021 [Link] GMT+0530 (India Standard Time)
Date Methods
- Here are some commonly used methods for working with Date objects:
Get Methods :
- ’getDate()’: Returns the day of the month (1-31) for a specific date.
var d = new Date();
[Link]([Link]()); // Example: 27 (for 27th of the month)
- ’getDay()’: Returns the day of the week (0-6) for a specific date (0 = Sunday,
6 = Saturday).
[Link]([Link]()); // Example: 15
[Link]([Link]()); // Example: 30
- ’getMonth()’: Returns the month (0-11) for the specified date (0 = January, 11
= December).
[Link]([Link]()); // Example: 45
Set Methods
- ’setDate()’: Sets the day of the month (1-31) for a specific date.
[Link](5);
[Link](2022);
- ’setHours()’: Sets the hour (0-23) for a specific date.
[Link](10);
[Link](500);
[Link](30);
[Link](45);
Expected Question :
1) List the various methods of Math object. Explain any one with example.
[Link](8); // Returns 2
[Link](3.4); // Returns 4
[Link]([Link]); // Returns -1
[Link](0); // Returns 1
- ’[Link](x, y, ...)’: Returns the square root of the sum of squares of the
given numbers (Euclidean distance).
[Link](3.5); // Returns 4
[Link](-5); // Returns -1
[Link](0); // Returns 0
[Link](16); // Returns 4
[Link](0); // Returns 0
[Link](3.7); // Returns 3
Number in JavaScript
- The Number object in JavaScript is used to represent numeric values, which
can either be integers or floating-point numbers.
- JavaScript follows the IEEE standard for representing floating-point numbers.
- If the value cannot be converted to a number, the result will be ‘NaN’ (Not a
Number).
[Link]("42"); // Returns 42
- ’toFixed(x)’: Returns a string representing the number with exactly ‘x’ digits
after the decimal point.
String in JavaScript
- A String in JavaScript is a sequence of characters enclosed in single or double
quotes.
- JavaScript does not distinguish between a single character and a string of
characters.
Creating a String
- There are two ways to create a string in JavaScript:
1. By string literal:
- Strings are associated with a String object, which provides several methods
for manipulating and examining strings.
- ’concat(str1, str2, ...)’: Joins two or more strings and returns the concatenated
string.
- ’substr(start, length)’: Returns a part of the string starting from ‘start’ index
and with ‘length’ characters.
- ’substring(start, end)’: Returns a part of the string between ‘start’ and ‘end’
index.
- ’slice(start, end)’: Extracts a part of the string and returns it as a new string.
Primitive Types
Primitive types in JavaScript include:
- String
- Number
- Boolean
- Undefined
- Null
- Symbol (new in ECMAScript 6)
- BigInt (for very large integers)
- These types are immutable (cannot be changed once created) and are passed
by value.
- This means when you assign a primitive value to a variable, a copy of the value
is stored, and any changes to the new variable do not affect the original variable.
Object Types
Objects in JavaScript are collections of properties and methods and include
types like:
- Object
- Array
- Function
- Date
- RegExp
- Error
- Map
- Set
- Objects are reference types, meaning they store a reference (or pointer) to
the location in memory where the actual data is stored.
- When an object is passed to a function, it's the reference that is passed,
allowing the function to modify the original object.
For example:
- You can create a String object using the ‘new String()’ constructor:
function modifyString(str) {
str = "Modified";
}
var primitiveStr = "Hello";
modifyString(primitiveStr);
[Link](primitiveStr); // Output: "Hello", original string remains
unchanged
function modifyObject(obj) {
[Link] = "Changed";
}
Q. Write a JavaScript program that will append an object to an array and will
check if an object is an array data types.
// Main code
// Creating two objects with 'value' properties
let object1 = { value: 10 };
let object2 = { value: 20 };
Explanation
- Function ‘addObjects(obj1, obj2)’: This function takes two objects as
parameters (‘obj1’ and ‘obj2’) and adds their ‘value’ properties together. The
result is stored in ‘[Link]’ and also updated in ‘[Link]’.
- Objects (‘object1’, ‘object2’): Initially, the objects contain ‘value’ properties
with numbers (‘[Link] = 10’, ‘[Link] = 20’).
- Displaying the result: Before and after calling the function, we print the values
of the objects using ‘[Link]()’ to show the result of the addition.
Output
Before Addition:
Object 1 value: 10
Object 2 value: 20
After Addition:
Object 1 value: 30
Object 2 value: 30
JavaScript program that will append an object to an array and will check if an
object is an array data types.
JavaScript Code:
Explanation:
4. ‘[Link]()’:
- ‘[Link](myObject)’ checks if ‘myObject’ is an array. It will return
‘false’ because ‘myObject’ is an object, not an array.
- ‘[Link](myArray)’ checks if ‘myArray’ is an array. It will return ‘true’
because ‘myArray’ is an array, even though it now contains an object.
5. Final Output:
- The program first checks if ‘myObject’ is an array and prints ‘false’.
- Then it checks if ‘myArray’ is an array and prints ‘true’.
- Finally, it prints the updated content of ‘myArray’, showing that ‘myObject’
is successfully appended.
Output:
Updated Array:
[ 'apple', 'banana', 'cherry', { name: 'John', age: 30 } ]
Unit -4 Regular Expressions
Expected Question :
-> What is Regular Expression in JavaScript and explain the need of regular
expressions.
-> Explain Look ahead and Look behind concepts in JavaScript.
-> Write a program to study string related built-in methods in JavaScript.
-> Explain string methods for Regular Expression in JavaScript.
-> Explain Character Classes in JavaScript.
-> What are the limitations of Regular Expression?
-> What are common character classes in Regular Expressions?
-> Write a short note on Advanced Regular Expressions.
-> List String Methods for Regular Expressions and explain any one of them.
-> List the 6 Repetition Quantifiers with their meaning. Explain any 2 with
example.
-> Explain Static Properties of the RegExp Class Object.
-> Describe Limitations of Regular Expressions.
Regular Expressions in JavaScript
Expected Question :
1) What is Regular Expression in JavaScript and explain the need of
regular expressions.
- Regular expressions (RegExp) are patterns used for matching and manipulating
strings.
- They are commonly used for validating input, parsing text, and performing
search-and-replace operations.
- JavaScript introduced regular expressions with the ‘RegExp’ object.
2. Validation: Validates user input like phone numbers, email addresses, etc.
3. Search and Replace: Simplifies tasks like finding specific patterns and
replacing them with new content.
function isDigit(character) {
return character >= '0' && character <= '9';
}
function isPhoneNumber(phone) {
if ([Link] !== 12) return false;
function isPhoneNumber(phone) {
var phoneRegex = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
return [Link](phone);
}
- Anchors:
- ‘^’ matches the start of a string.
- ‘$’ matches the end of a string.
- Quantifiers:
- ‘{n}’: Matches exactly n occurrences.
- ‘{n,}’: Matches at least n occurrences.
- ‘{n,m}’: Matches between n and m occurrences.
- ‘*’: Matches 0 or more occurrences.
- ‘+’: Matches 1 or more occurrences.
- ‘?’: Matches 0 or 1 occurrence.
- Character Classes:
- ‘[0-9]’: Matches a single digit.
- ‘[a-zA-Z]’: Matches a single letter (lowercase or uppercase).
- ‘.’: Matches any single character except newline.
- ‘\d’: Matches any digit (equivalent to ‘[0-9]’).
- ‘\D’: Matches any non-digit.
- ‘\w’: Matches any word character (alphanumeric + ‘_’).
- ‘\W’: Matches any non-word character.
- URL:
var urlRegex = /^(https?:\/\/)?(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\/?$/;
[Link]([Link]("[Link] // true
Key Methods:
1. ‘test()’: Checks if a string matches the pattern.
javascript
/abc/.test("abcdef"); // true
Creating Patterns:
- Regular expressions can be created in two ways:
1. Literal Syntax:
javascript
var pattern = /http/;
Example:
Positional Indicators:
These special characters ensure that patterns match specific parts of a
string:
- ‘^’ Matches the beginning of a string.
- ‘$’ Matches the end of a string.
Examples:
- Beginning Match:
var pattern = /^http/;
var str = "http is a protocol";
[Link](str); // true
- End Match:
var pattern = /http$/;
var str = "The protocol is http";
[Link](str); // true
- Exact Match:
var pattern = /^http$/;
var str1 = "http";
var str2 = "http is used";
[Link](str1); // true
[Link](str2); // false
Example:
To match the URL pattern ‘[Link] you must escape ‘/’ and ‘.’:
var pattern = /http:\/\/www\.w3c\.org\//;
Here:
- ‘\/’ escapes ‘/’.
- ‘\.’ escapes ‘.’.
Example Usage:
Expected Question :
1) List the 6 Repetition Quantifiers with their meaning. Explain any 2 with
example.
- Repetition quantifiers specify how many times the preceding element must
appear in a string for a match.
- Here is an explanation with examples for better understanding:
Examples of Quantifiers
5. Curly Braces with Range (‘{m,n}’) – Between ‘m’ and ‘n’ Occurrences:
This quantifier specifies a range for how many times the preceding character
can appear.
6. Curly Braces with Lower Limit Only (‘{m,}’) – At Least ‘m’ Occurrences:
This quantifier ensures the preceding character appears at least ‘m’ times with
no upper limit.
- Matches a string that starts with two digits, a hyphen, two more digits,
another hyphen, and four digits, ending there.
4. Lazy Quantifiers:
Lazy quantifiers make the match as short as possible.
- Matches "12" followed by two groups of "-34" and "-56", but does not capture
them.
Example 1:
- Explanation: The pattern ‘(ab)+’ matches "ab" one or more times in the string.
Here, "ab" repeats multiple times, so the result is "ab".
- Reading the pattern: "a" followed by "b", repeated one or more times.
Example 2:
1. Capture Groups:
- Parentheses also create *capture groups*. These are parts of the matched
pattern that can be referenced later in the regular expression or extracted
from the match results.
Example 3:
var pattern = /(\d{3})-(\d{3})-(\d{4})/;
var str = "123-456-7890";
var result = [Link](pattern);
[Link](result); // Output: ['123-456-7890', '123', '456', '7890']
- Explanation: The pattern creates three capture groups, one for each section
of the phone number. The result is an array where the first element is the entire
match, followed by each captured group (the three parts of the phone number).
2. Non-Capturing Groups:
- If you need to group a part of the regular expression but don’t want to
capture it (i.e., it is not needed in the result array), you can use a *non-capturing
group* with ‘(?:...)’.
Example 4:
Example 5:
var pattern = /(cat|dog)+/;
var str = "catdogcat";
var result = [Link](pattern);
[Link](result); // Output: 'catdogcat'
- Explanation: The alternation operator ‘|’ inside the group matches either
"cat" or "dog" one or more times. In this example, the pattern matches the string
"catdogcat".
4. Nested Groups:
- Groups can be nested inside other groups, which helps create more complex
matching patterns.
Example 6:
var pattern = /((ab){2})+/;
var str = "abababab";
var result = [Link](pattern);
[Link](result); // Output: 'abababab'
- Explanation: The pattern ‘((ab){2})+’ first groups "ab", then repeats it exactly
two times, and this sequence can repeat one or more times.
- This allows "abababab" to match the pattern.
Example 7:
var pattern = /(ab){3,5}/;
var str = "ababababab";
var result = [Link](pattern);
[Link](result); // Output: 'ababababab'
- Explanation: The pattern matches the group "ab" repeated between 3 and 5
times. In this case, it matches "ababababab".
Character Classes in Regular Expressions
Expected question :
1) Explain Character Classes in JavaScript.
2) What are common character classes in Regular Expressions?
- Character classes allow you to match any character from a specified set or
group.
- They are defined within square brackets ‘[]’. Anything inside the brackets is
treated as a single unit that can match any one character from the set.
Example 1:
var pattern = /[pbm]111/;
var str = "p111";
var result = [Link](pattern);
[Link](result); // Output: ['p111']
- Explanation: The class ‘[pbm]’ matches any one of the characters ‘p’, ‘b’, or
‘m’ followed by ‘111’. This will match ‘p111’, ‘b111’, and ‘m111’, but not ‘c111’.
2. Matching Digits:
- You can define a class to match digits using ‘0-9’ or specify them individually.
Example 2:
var pattern = /[1234567890]+/;
var str = "123456";
var result = [Link](pattern);
[Link](result); // Output: ['123456']
- Explanation: The pattern ‘[1234567890]’ matches any digit from 0 to 9. The
‘+’ quantifier means the pattern will match one or more digits.
Example 3:
var pattern = /[0-9]+/;
var str = "987654";
var result = [Link](pattern);
[Link](result); // Output: ['987654']
- Explanation: The pattern ‘[0-9]’ matches any digit, the same as ‘[1234567890]’,
but more compactly. This matches strings containing one or more digits.
1. Lowercase Letters:
var pattern = /[a-z]+/;
var str = "hello";
var result = [Link](pattern);
[Link](result); // Output: ['hello']
3. Alphanumeric Characters:
var pattern = /[a-zA-Z0-9]+/;
var str = "abc123";
var result = [Link](pattern);
[Link](result); // Output: ['abc123']
Example 4:
var pattern = /[^a-zA-Z]+/;
var str = "12345!";
var result = [Link](pattern);
[Link](result); // Output: ['12345!']
- Explanation: The pattern ‘[^a-zA-Z]’ matches any character that is not a letter
(either lowercase or uppercase). In this example, it matches the digits and
special characters in the string.
Example 5:
var pattern = /[^,]+, [^,]+, [^,]+, [^,]+, [^,]+/;
var str = "peter, paul, mary, larry, moe";
var result = [Link](str);
[Link](result); // Output: true
- Explanation: This is a more concise version of the previous pattern, using ‘(,
[^,]+){4}’ to match the repeated comma-separated values.
Practical Example:
To test for five comma-separated values:
Expected Question :
What are common character classes in Regular Expressions?
1. ‘.’ (Period)
- The period matches any single character except for newline characters. This
is useful when you want to match any character in a string.
Example:
var pattern = /abc..d/;
var str = "abcX7d";
var result = [Link](pattern);
[Link](result); // Output: ['abcX7d']
- Explanation: The pattern ‘abc..d’ matches any string that starts with ‘abc’,
followed by any two characters, and ends with ‘d’.
Example:
var pattern = /\w+/;
var str = "Hello123";
var result = [Link](pattern);
[Link](result); // Output: ['Hello123']
- Explanation: The pattern ‘\w+’ matches one or more word characters.
Example:
var pattern = /\W+/;
var str = "Hello 123!";
var result = [Link](pattern);
[Link](result); // Output: [' ']
- Explanation: The pattern ‘\W+’ matches one or more non-word characters, such
as spaces, punctuation, etc.
Example:
var pattern = /\s+/;
var str = "Hello world!";
var result = [Link](pattern);
[Link](result); // Output: [' ']
Example:
var pattern = /\S+/;
var str = "Hello world!";
var result = [Link](pattern);
[Link](result); // Output: ['Hello']
6. ‘\d’ (Digit)
- Matches any digit, equivalent to ‘[0-9]’.
Example:
var pattern = /\d+/;
var str = "12345";
var result = [Link](pattern);
[Link](result); // Output: ['12345']
7. ‘\D’ (Non-Digit)
- Matches any character that is not a digit, equivalent to ‘[^0-9]’.
Example:
var pattern = /\D+/;
var str = "abc123";
var result = [Link](pattern);
[Link](result); // Output: ['abc']
Example:
var pattern = /\bword\b/;
var str = "word boundary test";
var result = [Link](pattern);
[Link](result); // Output: ['word']
- Explanation: The pattern ‘\bword\b’ matches the word ‘word’ only when it is a
separate word (i.e., not part of another word like ‘sword’).
Example:
var pattern = /\Bword\B/;
var str = "sword";
var result = [Link](pattern);
[Link](result); // Output: ['word']
- You can use the pipe (‘|’) operator to define alternatives within a regular
expression.
- It works like a logical OR, where the pattern will match any one of the options.
Example:
var pattern = /(James|Jim|Charlie) Brown/;
var str = "James Brown";
var result = [Link](pattern);
[Link](result); // Output: ['James Brown']
- Explanation: The pattern ‘(James|Jim|Charlie) Brown’ matches "James Brown",
"Jim Brown", or "Charlie Brown".
Incorrect Example:
var pattern = /^http|ftp|https/;
var str = "ftp is file transfer protocol";
var result = [Link](pattern);
[Link](result); // Output: ['ftp']
1. Literal Syntax:
var pattern = /abc/;
This is the simplest and most common way to define a regular expression.
1. ‘test()’
- The ‘test()’ method is the simplest RegExp method and returns a Boolean value
indicating whether a given string matches the regular expression.
Example:
var pattern = /http/;
var str = "http is a protocol";
[Link]([Link](str)); // Output: true
2. ‘compile()’
- The ‘compile()’ method is used to replace an existing regular expression with a
new one. It takes the same arguments as the ‘RegExp’ constructor.
Example:
var pattern = new RegExp("http", "i");
[Link]("http+", "i");
[Link]([Link]("http is a protocol")); // Output: true
- Return Value: The ‘exec()’ method returns an array with various properties:
- ‘input’: The original input string.
- ‘index’: The position where the match starts.
- ‘lastIndex’: The position where the next match will start.
Example:
var pattern = /cat/;
var str = "He is a big cat, a fat black cat named Rufus.";
var result = [Link](str);
[Link](result);
- Output:
[
"cat", // Full match
index: 13, // Starting position of the match
input: "He is a big cat, a fat black cat named Rufus.", // The original string
lastIndex: 16 // Next search will begin after this index
]
Example:
var pattern = /(cat) (and) (dog)/;
var str = "My cat and dog are black.";
var result = [Link](str);
[Link](result);
- Output:
[
"cat and dog", // Full match
"cat", // First subexpression (cat)
"and", // Second subexpression (and)
"dog", // Third subexpression (dog)
length: 4, // Total number of elements in the result
index: 3, // Position where the match starts
input: "My cat and dog are black." // The original string
]
- Explanation: In this case, the pattern ‘/(cat) (and) (dog)/’ matches the string
"cat and dog" and captures "cat", "and", and "dog" as separate subexpressions.
Example of Sub-Expressions
- Consider a scenario where you want to extract first names and phone numbers
from a string that follows the format: ‘Firstname Lastname NNN-NNNN’ (where
‘N’ represents digits of a phone number).
You can use the following regular expression:
var pattern = /(\w+)\w+([\d-]{8})/;
- When this regular expression matches a string, the portions inside the
parentheses are saved as sub-expressions.
- You can access these captured substrings using special properties ‘$1’ to ‘$9’
from the ‘RegExp’ object.
Example:
var pattern = /(\w+)\w+([\d-]{8})/;
var str = "Alan Turing 555-1212";
if ([Link](str)) {
alert("RegExp.$1 = " + RegExp.$1); // Output: "Alan"
alert("RegExp.$2 = " + RegExp.$2); // Output: "555-1212"
}
- Explanation:
- The first sub-expression ‘(\w+)’ captures ‘"Alan"‘, and this can be accessed
via ‘RegExp.$1’.
- The second sub-expression ‘([\d-]{8})’ captures ‘"555-1212"‘, and this can be
accessed via ‘RegExp.$2’.
RegExp Properties
- JavaScript's ‘RegExp’ object has several properties that can be useful for
debugging and understanding regular expressions.
- These properties provide details about the state of the regular expression
instance.
Instance Properties
1. global
- Type: Boolean
- Description: Indicates if the global (‘g’) flag is set.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // true
2. ignoreCase (i)
- Type: Boolean
- Description: Indicates if the case-insensitive (‘i’) flag is set.
- Example:
javascript
var pattern = /(cat)(dog)/i;
[Link]([Link]); // true
3. lastIndex
- Type: Integer
- Description: Specifies the position in the string where the next match will
begin. Can be modified directly.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 17
4. multiline (m)
- Type: Boolean
- Description: Indicates if the multiline (‘m’) flag is set.
- Example:
javascript
var pattern = /(cat)(dog)/m;
[Link]([Link]); // true
5. source
- Type: String
- Description: The string form of the regular expression (without flags).
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]([Link]); // "(cat)(dog)"
Expected Question :
b) Explain Static Properties of the RegExp Class Object.
- These properties are accessed from the ‘RegExp’ class and are used to handle
results from the most recent match.
2. index
- Type: Integer
- Description: The position of the first character of the last match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 10
3. input
- Type: String
- Description: The string that was tested against the regular expression.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "this is a cat dog and cat dog"
4. lastIndex
- Type: Integer
- Description: Specifies the position in the string where the next match will
begin, for global matches.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 17
5. lastMatch
- Type: String
- Description: Contains the most recently matched text.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "cat dog"
6. lastParen
- Type: String
- Description: Contains the text of the last parenthesized subexpression of
the most recent match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "dog"
7. leftContext
- Type: String
- Description: Contains the text to the left of the most recent match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "this is a "
8. rightContext
- Type: String
- Description: Contains the text to the right of the most recent match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // " and cat dog"
Dynamic Scoping of Static Properties
- Static properties of ‘RegExp’ are dynamically scoped, meaning they reflect the
context of the most recent regular expression operation, not the scope in which
the regular expression was defined.
- This is especially important when working with regular expressions across
different contexts, such as in frames or multiple function calls.
Expected Question :
a) Explain string methods for Regular Expression in JavaScript.
- The ‘String’ object offers several methods that work with regular expressions,
providing powerful tools for string manipulation.
- These methods not only match patterns but can also modify strings based on
those patterns.
1. ‘search()’
- Purpose: Finds the index of the first match of a regular expression within a
string.
- Returns: The index of the first matching substring or ‘-1’ if no match is found.
- Example:
var pattern = /pow.*/i;
var str = "JavaScript regular expressions are powerful!";
var result = [Link](pattern);
[Link](result); // Prints: 35 (index of "powerful!")
2. ‘split()’
- Purpose: Splits a string into an array of substrings using a regular expression
as the delimiter.
- Example:
var str = "I am, string, break it.";
var result = [Link](",");
[Link](result); // Prints: ["I am", " string", " break it."]
- With Regular Expressions: You can split based on patterns like spaces or
slashes.
javascript
var limiter = /[\/]+/; // one or more slashes
var str = "10/3/14/7/9";
var result = [Link](limiter);
[Link](result); // Prints: ["10", "3", "14", "7", "9"]
3. ‘replace()’
- Purpose: Replaces the first occurrence of a pattern in a string with a
replacement string.
- Example:
var pattern = /\./;
var newStr = "1";
var str = "Hello. Regexps are fun.";
var result = [Link](pattern, newStr);
[Link](result); // Prints: "Hello1 Regexps are fun."
- With Global Flag: Use the ‘g’ flag to replace all occurrences.
javascript
var pattern = /\./g;
var newStr = "1";
var str = "Hello. Regexps are fun.";
var result = [Link](pattern, newStr);
[Link](result); // Prints: "Hello Regexps are fun!"
4. ‘replace() with Subexpressions’
- Purpose: Replace portions of a string using back-references to regular
expression groups.
- Example:
var pattern = /(\d{3})(\d{2})(\d{4})/;
var newStr = "$1-$2-$3";
var str = "123456789";
var result = [Link](pattern, newStr);
[Link](result); // Prints: "123-45-6789"
5. ‘match()’
- Purpose: Finds all occurrences of a regular expression in a string and returns
them in an array.
- Example:
var pattern = /\d{2}/g;
var str = "22, 48, 13, 17, 26";
var result = [Link](pattern);
[Link](result); // Prints: ["22", "48", "13", "17", "26"]
Each of these string methods provides useful ways to handle text based on
regular expressions, offering both matching and manipulation features.
Expected Question :
b) Write a short note on Advanced Regular Expressions.
1. Multiline Matching
- Purpose: The multiline flag (‘m’) allows the characters ‘^’ and ‘$’ to match not
only the beginning and end of the entire string but also the beginning and end of
each line within the string.
- Example 1:
javascript
var str = "Is this all there\nis";
var pattern = /^is/m; // ^ matches the beginning of a line, m flag enables
multiline matching
var result = [Link](pattern);
[Link](result); // Output: ["is"]
Here, ‘^’ matches "is" at the start of the third line, thanks to the ‘m’ flag.
- Example 2:
var str = "This text has multiple lines. \nThis is the second line.\nThe third.";
var pattern = /^.*$/gm; // ^ matches the beginning of a line, $ matches the
end of the line, g flag matches all lines
var result = [Link](pattern);
[Link](result);
// Output:
// ["This text has multiple lines.", "This is the second line.", "The third."]
- This example shows how the ‘m’ flag allows matching entire lines, using ‘^’ to
match the beginning and ‘$’ for the end of each line.
2. Non-Capturing Parentheses
- Purpose: Non-capturing parentheses, written as ‘(?:...)’, are used when you want
to group parts of a regular expression without saving those parts for back
referencing. This can be useful when you do not need to refer back to a part of
the match but still want to group expressions together for clarity.
- Example:
var str = "aaaaaabcd";
var pattern = /(?:a+)(bcd)/; // The non-capturing group (a+) will not be saved
for later reference
var result = [Link](str); // Executes the regular expression
[Link](result[1]); // Output: "bcd"
- In this example, ‘(?:a+)’ does not capture the sequence of "a"s, but the ‘bcd’
part is captured as the first group.
3. Lookaround Groups
- Purpose: Lookaround groups are used to match text only if it is followed or
preceded by a specific pattern, without including the followed or preceded text
in the match. There are four types of lookaround groups:
- Positive Lookahead (‘(?=...)’): Matches a pattern only if it is followed by
another pattern.
- Negative Lookahead (‘(?!...)’): Matches a pattern only if it is not followed by
another pattern.
- Positive Lookbehind (‘(?<=...)’): Matches a pattern only if it is preceded by
another pattern.
- Negative Lookbehind (‘(?<!...)’): Matches a pattern only if it is not preceded by
another pattern.
- Here, the lookahead ‘(?=abc)’ ensures that the digit "3" is matched only if it
is followed by "abc".
- This negative lookahead ensures that digits followed by "abc" are excluded
from the match, leaving digits not followed by "abc" as the matches.
In this example, the negative lookbehind ‘(?<!abc)’ ensures that any digit
preceded by "abc" is excluded. Hence, the digits that are not preceded by "abc"
are matched.
- These advanced techniques allow you to create highly flexible and complex
patterns, providing much more control over string matching and manipulation.
Expected Question :
1) Explain Look ahead and Look behind concepts in JavaScript.
Lookahead :
- A lookahead group is a non-capturing group that allows you to match a part of
a string only if it is followed by a specific sequence of characters, without
including that sequence in the match itself.
- There are two types of lookaheads: positive lookahead and negative lookahead.
- Example:
var pattern = /x(?=y)/;
var str = "SCOE-E&TC";
var result = [Link](pattern);
[Link](result); // Output: ["x"]
In this example, the pattern ‘/x(?=y)/’ will match ‘x’ only if it is followed by ‘y’.
The ‘y’ is not included in the match.
In this case, the pattern ‘/x(?!y)/’ will match ‘x’ only if it is not followed by ‘y’.
If ‘x’ were followed by ‘y’, the match would not occur.
Both positive and negative lookaheads do not include the pattern inside the
lookahead in the final match; they only assert whether the condition is true or
false.
Lookbehind :
- Example:
var pattern = /(?<=x)y/;
var str = "SCOE-E&TC";
var result = [Link](pattern);
[Link](result); // Output: ["y"]
Here, the pattern ‘/y(?<=x)/’ will match ‘y’ only if it is preceded by ‘x’. So, "xy"
would match, but "xx" or "yx" would not.
- Example:
var pattern = /(?<!x)y/;
var str = "SCOE-E&TC";
var result = [Link](pattern);
[Link](result); // Output: ["y"]
- In this case, the pattern ‘/(?<!x)y/’ will match ‘y’ only if it is not preceded by
‘x’. So, "by" would match, but "xy" would not.
Greedy Matching
- Greedy matching means the regular expression tries to match as many
characters as possible.
- The engine looks for the longest possible match and if not found, removes the
last character and reattempts.
- Example:
var pattern = /(ma.*ing)/;
var str = "Regexp matching can be daunting.";
[Link](str);
alert(RegExp.$1);
- The result is "matching can be daunting" because the ‘.*’ quantifier matches
the longest substring possible.
Expected Question :
c) What are the limitations of Regular Expression?
4. Real-world Validation:
- Email Addresses: Difficult to validate due to complex formats (e.g., ‘!’ or ‘+’
symbols, IP addresses).
- Phone Numbers: Different formats in various countries make it hard to
validate with regex alone.
- Credit Card Numbers: Regex can check the format, but not the actual validity
(e.g., through Luhn's algorithm).
5. Semantic Validity: Regex can validate the format but not check if the data is
logically correct (e.g., ‘31/02/2021’).
Regular expressions are useful for basic validation, but for more complex
scenarios, additional logic is often required.
Some pyq’s program
// Step 5: Using indexOf() method to find the position of the first occurrence
of a substring
[Link]("Index of 'World': " + [Link]("World")); // Output: 19
// Step 10: Using trim() method to remove whitespaces from both ends of the
string
let trimmedString = [Link]();
[Link]("Trimmed String: '" + trimmedString + "'");
// Step 11: Using split() method to split the string into an array based on a space
let stringArray = [Link](" ");
[Link]("String Split into Array: ", stringArray);
1. ‘charAt(index)’:
This method is used to get a character from a string at a specific index. In
our case, ‘[Link](6)’ returns ‘'J'‘ because ‘'J'‘ is the character at
index 6 in the string ‘"Hello, JavaScript World!"‘.
2. ‘concat()’:
The ‘concat()’ method is used to merge two or more strings. Here, the original
string ‘myString’ is concatenated with the string ‘" Enjoy Learning!"‘, producing
a new string: ‘" Hello, JavaScript World! Enjoy Learning!"‘.
3. ‘includes()’:
This method checks if a string contains a specific substring. We check if
‘"JavaScript"‘ is present in ‘myString’. Since it is, the method returns ‘true’.
4. ‘indexOf()’:
The ‘indexOf()’ method returns the index of the first occurrence of a
specified substring. In our case, it returns ‘19’ because the substring ‘"World"‘
starts at index 19.
5. ‘toUpperCase()’:
This method converts all characters in the string to uppercase. For ‘myString’,
it converts ‘" Hello, JavaScript World! "‘ to ‘" HELLO, JAVASCRIPT WORLD!
"‘.
6. ‘toLowerCase()’:
This method converts all characters in the string to lowercase. For ‘myString’,
it converts ‘" Hello, JavaScript World! "‘ to ‘" hello, javascript world! "‘.
7. ‘slice(startIndex, endIndex)’:
The ‘slice()’ method extracts a section of a string. We extract characters
from index ‘3’ to ‘10’, which results in ‘"llo, Ja"‘.
8. ‘replace(searchValue, newValue)’:
The ‘replace()’ method replaces the first occurrence of a substring with
another substring. We replace ‘"JavaScript"‘ with ‘"[Link]"‘, resulting in ‘"
Hello, [Link] World! "‘.
9. ‘trim()’:
This method removes any leading and trailing whitespace from the string.
After trimming, the string ‘" Hello, JavaScript World! "‘ becomes ‘"Hello,
JavaScript World!"‘.
10. ‘split(separator)’:
The ‘split()’ method splits a string into an array of substrings based on the
separator. Here, the string is split into an array of words using ‘" "‘ (space) as
the separator. The resulting array is: ‘["Hello,", "JavaScript", "World!"]’.
Output:
Character at index 6: J
Concatenated String: Hello, JavaScript World! Enjoy Learning!
Does the string contain 'JavaScript'? true
Index of 'World': 19
Uppercase String: HELLO, JAVASCRIPT WORLD!
Lowercase String: hello, javascript world!
Sliced String (from index 3 to 10): llo, Ja
Replaced String: Hello, [Link] World!
Trimmed String: 'Hello, JavaScript World!'
String Split into Array: [ 'Hello,', 'JavaScript', 'World!' ]
Unit-5: Fundamental Client-Side JavaScript and Event Handling
Expected question :
-> Define JavaScript object model and explain four distinct object models used
in JavaScript.
-> Explain event and event handler with an example.
-> Write a JavaScript program to create a Home page of any website and
change background color using.
On mouse over event (mouse over)
On focus event (focus)
-> Describe Document properties and methods with their HTML relationship.
-> Differentiate between HTML and DHTML.
-> Explain DOM and CSS Elements with example.
Object Model
Expected Question :
1) Define JavaScript object model and explain four distinct object models
- JavaScript interacts with various parts of the browser and document through
several layers of objects. These are divided into categories:
2. Built-in Objects:
- JavaScript provides built-in objects that help manage data and other tasks.
These include:
- Math: Provides mathematical constants and functions (e.g., [Link],
[Link]()).
- String: Offers methods for string manipulation (e.g., ‘toUpperCase()’,
‘substring()’).
- Number: Used for handling numerical values.
- Array: A collection of values indexed by numbers, with methods to
manipulate them.
- Date: For working with dates and times.
- RegExp: Provides regular expression functionality for pattern matching.
1. Window Object:
- Represents the entire browser window.
- It allows interaction with the browser, like showing alerts or opening new
windows.
- Example: ‘[Link]("Hello")’. In JavaScript, we usually write it as
‘alert("Hello")’, but it refers to the ‘window’ object by default.
2. document Object:
- Contains all the elements of the webpage, like buttons, text boxes, and other
HTML content.
- JavaScript can interact with these elements to read or change the content
on the page.
3. frames[] Object:
- If the page contains multiple frames (like in a frameset), this object holds
references to each frame in an array.
- Each frame is a separate ‘Window’ object that can also have its own content.
4. history Object:
- Tracks the page history (the URLs the user has visited).
- Methods like ‘[Link]()’ or ‘[Link]()’ allow you to move through
the history of visited pages.
5. location Object:
- Represents the URL of the current page.
- Allows you to retrieve or modify the URL (e.g., ‘[Link] =
"[Link] to change the page).
6. navigator Object:
- Provides information about the browser, like its name and version.
- Can be used to check if certain features (such as cookies) are supported by
the browser.
Basic Example:
// Using the window object to show an alert
[Link]("This is a message"); // This is the same as just writing:
alert("This is a message"); // JavaScript assumes it's using the window object.
Document Object
- The Document object provides access to various elements within the web page,
such as anchors, form fields, links, and page properties like background color
and text color.
- It allows JavaScript to interact with the structure and content of the
webpage.
- However, the structure of the Document object can differ significantly
between different browsers and versions.
Document Properties:
Pyq’s Question :
1) Describe Document properties and methods with their HTML
relationship.
- alinkColor: The color of active links (links clicked by the user), typically red by
default
- forms[]: An array containing all the form elements (‘<form>‘) in the document.
- links[]: An array of all the link elements (‘<a href="URL">‘) in the document.
- linkColor: The color of unvisited links, typically blue by default.
- lastModified: A string containing the date when the document was last
modified.
if ([Link] > 0) {
[Link]("<h2>Links</h2>");
[Link]("# Links = " + [Link] + "<br>");
for (var i = 0; i < [Link]; i++) {
[Link]("Links[" + i + "] = " + [Link][i] + "<br>");
}
}
if ([Link] > 0) {
[Link]("<h2>Anchors</h2>");
[Link]("# Anchors = " + [Link] + "<br>");
for (var i = 0; i < [Link]; i++) {
[Link]("Anchors[" + i + "] = " + [Link][i] + "<br>");
}
}
if ([Link] > 0) {
[Link]("<h2>Forms</h2>");
[Link]("# Forms = " + [Link] + "<br>");
for (var i = 0; i < [Link]; i++) {
[Link]("Forms[" + i + "] = " + [Link][i].name + "<br>");
}
}
- Many of these properties will not be set unless you run the script on a document
containing specific elements (forms, links, etc.).
- For example, if no ‘<form>‘ is present in the document, the ‘forms[]’ property
will be empty.
- Browsers may define default values for certain properties like text and link
colors, even if the corresponding HTML elements or attributes are not present.
- This allows you to target specific elements within a form based on their
position.
- Downside:
The major downside of using position-based access is that if the order of the
elements or forms changes in the document, the JavaScript code may break or
reference the wrong element. A more robust approach is to use names instead
of positions.
For example:
- Many arrays in the Document object are associative, which means elements can
be accessed using names instead of numerical indices.
Example:
[Link]("myForm2")
- This approach allows for more flexible and readable code compared to position-
based access.
Event Handlers
Expected Question :
1) Explain event and event handler with an example.
- Event handlers are the primary way in which JavaScript responds to user
actions, such as clicks or mouse movements.
- An event handler is a piece of JavaScript code associated with a specific part
of the document and a particular event.
- The code is triggered when the event occurs at that part of the document.
- These events are commonly used with form buttons, form fields, images, and
links.
- They are used for tasks like form validation and rollover effects for buttons.
- Not every object can handle every type of event. The types of events an object
can handle are typically linked to how that object is commonly used.
- When the user clicks the button, the browser sends a ‘Click’ event to the
button object, and its ‘onclick’ event handler is triggered.
- This is part of the Event Model in JavaScript, which defines how events are
handled and how event handlers are attached to objects.
<script type="text/javascript">
[Link] = new Function("alert('That tickles!')");
</script>
- You can also trigger events programmatically using JavaScript. For example,
you can call the ‘click()’ method on a button to trigger its ‘onclick’ event handler:
[Link]();
This will cause the same event to occur as if the user clicked the button.
Object Models and Evolution
- Over time, browser vendors have extended the functionality of the Document
Object Model (DOM).
- As new versions of browsers were released, additional features were added,
bugs were fixed, and the document's capabilities were enhanced.
- While the gradual evolution of the DOM allows for more powerful tasks, it
also introduces challenges for web developers.
- The biggest issue arises from the fact that different browsers developed
their object models in different ways.
- For example, Internet Explorer and Netscape introduced proprietary tags and
non-standard methods for handling Dynamic HTML (DHTML), which means that
DHTML code written for one browser often doesn't work on the other.
- This created compatibility problems for web developers who had to write
separate code for different browsers.
- However, as modern browsers have improved their support for DOM standards,
these differences have become less of an issue, making it easier for developers
to write cross-browser compatible code.
- Objects:
- ‘button’, ‘checkbox’, ‘anchors[]’, ‘applets[]’, ‘file’, ‘hidden’, ‘embeds[]’,
‘password’, ‘forms[]’, ‘elements[]’, ‘radio’, ‘images[]’, ‘reset’, ‘links[]’, ‘select[]’,
‘option[]’, ‘plugins[]’, ‘submit’, ‘text’.
The introduction of DHTML in Netscape 4 laid the groundwork for modern web
development techniques, allowing for more dynamic, responsive, and interactive
web pages.
This model was basic but functional for its time, supporting simple web
interactions like form handling and link navigation.
- Properties in IE4:
- all[]: Array of all HTML tags in the document (new to IE4).
- applets[]: Array of ‘<applet>‘ tags in the document.
- children[]: Array of all child elements of a specific object.
- embeds[]: Array of embedded objects (‘<embed>‘ tags).
- images[]: Array of ‘<img>‘ tags in the document.
- scripts[]: Array of ‘<script>‘ tags in the document.
- styleSheets[]: Array of ‘<style>‘ tags or CSS style objects in the document.
Key Enhancements:
- IE4 made it possible to access every HTML element, such as ‘<div>‘, ‘<span>‘, and
others, as objects within the JavaScript environment.
- It also introduced the ability to manipulate the page's CSS styles directly via
JavaScript, giving developers much more control over the document's
presentation and layout.
- The ‘styleSheets[]’ property allowed access to the stylesheets directly, making
it easier to modify styles dynamically.
DOM Levels
- The DOM is divided into several levels, each offering different features and
improvements over the previous version.
DOM Level 0
- This level is similar to the older object models used by Netscape 3.0 and
Internet Explorer 3.0.
- It supports basic document object collections like forms[], images[], anchors[],
links[], and applets[].
- This level is often referred to as the classic or traditional JavaScript object
model.
DOM Level 1 :
- This level allows developers to manipulate all elements in a document using a
common set of functions.
- It provides cross-browser compatibility, which was missing in earlier versions.
- In DOM Level 1, the page elements can be read and written at all times,
enabling dynamic changes to the web page.
DOM Level 2 :
- This level builds on DOM Level 1 by adding support for style sheet manipulation
and a more advanced event model.
- It also includes traversal and range operations, which allow more sophisticated
ways of navigating and modifying the document.
- Although it includes many useful features, not all browsers fully support the
features of DOM Level 2.
DOM Categories
The DOM specification divides the functionality into five main categories:
1. DOM Core:
- Defines a generic model for viewing and manipulating a document as a tree
structure.
- This is the base for all other DOM specifications.
2. DOM HTML:
- This is an extension to the core DOM for HTML documents.
- It allows manipulation of HTML elements and is similar to the traditional
JavaScript object model.
- It includes DOM Level 0 features plus the ability to manipulate all HTML
element objects.
3. DOM CSS:
- Provides interfaces to manipulate CSS rules programmatically.
- This allows JavaScript to change styles of elements dynamically.
4. DOM Events:
- Adds event handling to the DOM.
- Events range from user interface actions like mouse clicks to internal DOM-
specific events that occur when the document structure changes.
5. DOM XML:
- Extends the core DOM to work with XML documents.
- It handles specific needs for XML, such as CDATA sections, processing
instructions, and namespaces.
<!DOCTYPE html>
<html>
<head>
<title>DOM Implementation Test</title>
</head>
<body>
<h1>DOM Feature Support</h1>
<hr />
<script type="text/javascript">
var featureArray = ["HTML", "XML", "Core", "CSS2", "Events", "UIEvents",
"MouseEvents", "Traversal"];
var versionArray = ["1.0", "1.0", "2.0", "2.0", "2.0", "2.0", "2.0", "2.0"];
for(i=0; i<[Link]; i++){
var feature = featureArray[i];
var version = versionArray[i];
if([Link] && [Link]){
[Link](feature + " " + [Link](feature,
version));
[Link]("<br />");
}
}
</script>
</body>
</html>
- This script tests which features of the DOM are supported by the browser,
printing out the results for each feature.
- The ‘hasFeature()’ method checks whether a particular feature (like "HTML"
or "CSS2") is available in the current browser version.
- With the DOM standard, web developers can build more powerful, flexible, and
cross-browser-compatible websites and web applications.
Document Trees :
Pyq’s question :
1) What is Document Tree? Explain DOM Methods to Create Nodes.
- In DOM Level 1 and Level 2, the most important concept is that we are
manipulating a document tree.
- This tree structure represents the entire document as a hierarchical set of
nodes, where each node corresponds to a part of the document, such as
elements, attributes, or text.
<!DOCTYPE html>
<html>
<head></head>
<title>DOM Test</title>
<body>
<h1>DOM Test Heading</h1>
<hr />
<p>A paragraph of <em>text</em> is just an example</p>
<ul>
<li><a href="[Link]
</ul>
</body>
</html>
- There are several types of nodes in the DOM that relate to HTML or XML
documents:
1. Element Node (Type 1): Represents an element in the document, like ‘<html>‘,
‘<head>‘, ‘<body>‘, ‘<h1>‘, etc.
2. Attribute Node (Type 2): Represents an attribute of an element, such as
‘href="[Link] in an ‘<a>‘ tag.
3. Text Node (Type 3): Represents the actual text content inside an element.
For example, the text inside ‘<h1>DOM Test Heading</h1>‘ is a text node.
4. Comment Node (Type 8): Represents an HTML comment, like ‘<!-- This is a
comment -->‘.
5. Document Node (Type 9): The root node of the DOM tree, which represents
the entire document (typically the ‘<html>‘ element in an HTML document).
6. Document Type Node (Type 10): Represents the document type declaration
(like ‘<!DOCTYPE html>‘).
In the document provided above, the tree would look something like this:
Root Node: <html>
|
|-- <head>
|-- <title>DOM Test</title>
|-- <body>
|-- <h1>DOM Test Heading</h1>
|-- <hr />
|-- <p>A paragraph of <em>text</em> is just an example</p>
|-- <ul>
|-- <li><a href="[Link]
</ul>
Subtrees
- A subtree is any part of the DOM tree that is rooted at a specific node. For
example, consider this HTML fragment:
In this case, the ‘<p>‘ element is the parent of three child nodes:
- The first text node ("A paragraph of ")
- The second element node (‘<em>‘) which contains its own text node ("text")
- The third text node ("is just an example")
Node Relationships
- In a DOM tree, nodes are related to one another in various ways:
Accessing Elements
- When navigating through an HTML document tree, you can start from the root
or choose any specific element as the starting point.
- In the document below, the ‘<p>‘ tag can be uniquely identified using the ‘id’
attribute with the value ‘p1’:
<!DOCTYPE html>
<html>
<head>
<title>DOM Test</title>
</head>
<body>
<p id="p1" align="center">A paragraph of <em>text</em> is just an example</p>
</body>
</html>
[Link]('p1');
- This method returns a DOM element object representing the ‘<p>‘ tag. To
examine the object returned, you can use the following JavaScript:
- nodeName: Contains the name of the node (e.g., "P" for a ‘<p>‘ tag).
- nodeValue: Contains the value within the node. This is generally only applicable
to text nodes.
- nodeType: Holds a number corresponding to the type of the node (e.g., ‘1’ for
element nodes, ‘3’ for text nodes).
- parentNode: Reference to the parent node, if one exists.
- childNodes: A list of child nodes.
- firstChild: The first child node of the element.
- lastChild: The last child node of the element.
- previousSibling: The previous sibling of the node.
- nextSibling: The next sibling of the node.
- attributes: A list of attributes for the element.
- ownerDocument: Points to the HTML document object that contains the
element.
Browser Differences :
- Different browsers may represent the document tree slightly differently.
- For example, browsers like Opera, Netscape, and Mozilla-based browsers
include more nodes in the tree compared to Internet Explorer because
whitespace is also treated as a text node in these browsers.
- While this could cause differences in tree traversal, normalizing the Mozilla-
style DOM tree is possible but generally unnecessary for most use cases.
Other Access Properties
- While ‘getElementById()’ is commonly used, there are other methods useful
for accessing elements:
In some cases, you may want to start at the top of the document tree and
traverse down. Two useful properties for tree traversal are:
- Similarly, you can find elements within other elements. For example, to find all
‘<em>‘ tags inside a specific paragraph with the ID ‘p1’:
Creating Nodes
- The DOM provides several methods to create new nodes, which can be added
to the document tree.
- These methods are part of the ‘Document’ object and are used to create
elements, attributes, comments, and text nodes.
- createAttribute(name): Creates an attribute with the specified ‘name’.
Example:
var myAlign = [Link]("align");
Example:
var myComment = [Link]("Just a comment");
Example:
var myFragment = [Link]();
Example:
var myHeading = [Link]("h1");
Example:
var newText = [Link]("Some new text");
- Once nodes are created, they need to be inserted into the document tree.
- This can be done using the ‘insertBefore()’ and ‘appendChild()’ methods.
appendChild(newChild):
- This method is invoked on the node to which you want to append a child. It adds
‘newChild’ to the end of the list of children of the parent node.
Example:
var newNode = [Link]('b');
var newText = [Link]("Something to add!");
[Link](newText);
<b>Something to add!</b>
insertBefore(newChild, referenceChild):
- This method allows you to insert ‘newChild’ before a specific ‘referenceChild’.
Example of usage:
var newNode = [Link]('b');
var newText = [Link]("Something to add!");
[Link](newText);
Copying Nodes
- To copy an existing node, you can use the ‘cloneNode()’ method.
- This method takes a single Boolean argument that determines if the copied
node should include all of its child nodes (deep clone) or just the element itself
(shallow clone).
- cloneNode(deep): Creates a copy of the node. If ‘deep’ is ‘true’, it copies all
child nodes; if ‘false’, it only copies the node itself.
<!DOCTYPE html>
<html>
<head>
<title>Clone Demo</title>
</head>
<body>
<p id="pl">This is a paragraph for cloning <hr>More content</p>
<div id="inserthere" style="background-color: yellow;"></div>
<script type="text/javascript">
function cloneAndCopy(nodeId, deep) {
var toClone = [Link](nodeId);
var clonedNode = [Link](deep);
var insertPoint = [Link]('inserthere');
[Link](clonedNode);
}
</script>
</body>
</html>
- In this example, when you click the "Clone" button, it clones the ‘<p>‘ tag without
its children, and when you click the "CloneDeep" button, it clones the ‘<p>‘ tag
along with its children.
- The cloned node is then appended to the ‘<div>‘ with the ID ‘inserthere’.
- removeChild(child): This method removes the specified child node from the
DOM. It returns the removed node.
Example:
var newNode = [Link]("strong");
var newText = [Link]("strong element");
[Link](newText);
- Accessing a text node: You can access the text node within an element using
the ‘firstChild’ property of the element.
Example:
var textNode = [Link]('p1').firstChild;
- Modifying the text content: You can use the ‘data’ property of the text node
to change its content.
Example:
[Link] = "I've been changed!";
<!DOCTYPE html>
<html>
<head>
<title>Text Node Modifications</title>
</head>
<body>
<p id="p1">This is a test</p>
<script type="text/javascript">
var textNode = [Link]('p1').firstChild;
</script>
</body>
</html>
- This example allows you to interact with the text node of the paragraph.
- The buttons trigger different modifications to the text node, such as
appending data, inserting it at a specific position, splitting the node, or replacing
part of the text.
- To effectively work with the DOM, it’s important to be familiar with HTML
syntax, as many DOM properties correspond to HTML attributes.
The DOM provides corresponding properties for these attributes, such as:
- ‘align’ → ‘align’
- ‘id’ → ‘id’
- ‘class’ → ‘className’
- ‘style’ → ‘style’ (more specifically, it's an object in DOM Level 2)
- ‘title’ → ‘title’
- ‘lang’ → ‘lang’
- ‘dir’ → ‘dir’
- For example, the following code accesses the paragraph's ‘id’ in the DOM:
var element = [Link]('uniqueID');
[Link]([Link]); // Outputs: uniqueID
Event Handlers
-- You can also use DOM properties to set event handlers. For instance, in HTML:
Similarly:
- Attributes like ‘char’ and ‘charoff’ for the ‘<col>‘ tag are mapped to ‘ch’ and
‘choff’.
function deleteNode() {
var deleteSpot = [Link]('addHere');
if ([Link]()) {
var toDelete = [Link];
[Link](toDelete);
}
}
function showHTML() {
alert("Not easily performed without innerHTML");
}
</script>
</head>
<body>
<h1 style="text-align: center;">Simple DOM HTML Editor</h1>
<div id="addHere" style="background-color: #ffffcc; border: solid;"></div>
<br><br>
Explanation:
1. addElement(): This function creates the selected HTML element (e.g., ‘<B>‘,
‘<P>‘) and adds text to it, then appends it to the ‘addHere’ div.
2. deleteNode(): This function deletes the last child of the ‘addHere’ div.
3. showHTML(): Placeholder for showing the HTML content of the div (but a
simple alert is used here).
Pyq’s Question :
1) Explain DOM and CSS Elements with example.
Example:
<p id="myParagraph">This is a test</p>
1. Border-Related Properties:
- ‘border-bottom-style’ → ‘borderBottomStyle’
- ‘border-width’ → ‘borderWidth’
2. Font Properties:
- ‘font-family’ → ‘fontFamily’
- ‘font-size’ → ‘fontSize’
- ‘font-style’ → ‘fontStyle’
5. List Properties:
- ‘list-style’ → ‘listStyle’
- ‘list-style-image’ → ‘listStyleImage’
Dynamic Style Using Classes and Collections
- CSS classes are commonly used to apply styles to multiple elements. Consider
a simple CSS style sheet with two classes:
<style type="text/css">
.look1 { color: black; background-color: yellow; font-style: normal; }
.look2 { background-color: orange; font-style: italic; }
</style>
- You can easily change the class of this element with JavaScript to dynamically
update its appearance:
- This would change the paragraph's appearance to match the ‘.look2’ class.
- If you want to change the style of multiple elements, you can use methods like
‘getElementsByTagName()’ to access all elements of a particular type and then
modify each element's style.
- This loops through all the ‘<p>‘ elements and sets their text alignment to "left".
You can also access other properties of the stylesheet, such as:
This adds a rule that changes the color of all ‘<p>‘ elements to red.
[Link](0);
[Link][0].[Link] = 'blue';
- This changes the color property of the first CSS rule to blue. For Internet
Explorer, use:
[Link][0].[Link] = 'blue';
- Some JavaScript developers have avoided the complexity of the DOM Level 1
by relying on older-style collections such as ‘[Link][]’,
‘[Link][]’, and even proprietary collections like ‘[Link][]’.
- While these older methods are not fully standard, they are supported in DOM
Level 0 for compatibility with older browsers.
- Despite the limitations of certain parts of the DOM (such as adding content
dynamically), proprietary features (like ‘innerHTML’ in Internet Explorer) are
sometimes added to other browsers for ease of use.
- This makes DHTML (Dynamic HTML) features popular because they enable
dynamic manipulation of the document with relative ease.
- For example, using ‘innerHTML’ allows you to quickly add or modify HTML
content in a browser:
- This can be convenient for simpler tasks but may not be as flexible as working
directly with the DOM.
- This will show the inner HTML content of the ‘<p>‘ element, which includes the
‘<em>‘ tag and the text "test".
- You can also use ‘innerHTML’ to change the content of an element. For example,
to change the text inside a ‘<p>‘ tag:
- This will update the content of the ‘<p>‘ tag with the new text.
- ‘innerText’: This is like ‘innerHTML’ but it treats the content as plain text. If
you try to set HTML tags in the text, they will not be rendered as HTML.
[Link] = "<b>test</b>";
[Link] = "<b>test</b>";
This will remove the ‘<p>‘ element and replace it with ‘<b>test</b>‘.
‘[Link][]’
- For example, here's how you could simulate ‘[Link][]’ using the DOM:
if (![Link]) {
[Link] = [Link]("*");
}
- This code will display all the tags in the document, similar to how ‘[Link][]’
would.
Example Code
<!DOCTYPE html>
<html>
<head>
<title>DOM Test</title>
</head>
<body>
<p id="p1" align="center">A paragraph of <em>text</em> is just an example</p>
<br>
<script type="text/javascript">
if (![Link]) {
[Link] = [Link]("*");
}
alert(allTags);
</script>
</body>
</html>
Output :
HTML
HEAD
BODY
P
BR
SCRIPT
- This example shows how you can loop through all the tags in the document and
display their names.
Pyq’s question :
1) Differentiate between HTML and DHTML.
HTML vs DHTML
Expected Question :
1) Explain event and event handler with an example.
Event Model:
- Events are crucial for interactive web pages. When a user interacts with a web
page, an event is triggered, and JavaScript can respond by executing event
handlers.
- The event model defines how events are processed and associated with
elements on the page.
Event Handlers:
- An event handler is JavaScript code that runs in response to a specific event.
- For example, a button click can trigger a pop-up window, or a form field change
can trigger data validation.
Event Object:
- When an event occurs, the browser provides an Event object containing details
about the event, such as the target element (the HTML element where the event
occurred).
- The basic event model is widely supported and simple to understand, with
enough features for most developers.
- It is compatible with both proprietary browser models and the newer DOM2
event model, which offers more flexibility and advanced features for complex
web applications.
Example:
- In this example, when the link is clicked, an alert box will pop up saying
"Proceeding to DOM."
For example:
- In this example, the click handler for the button is set using JavaScript.
- When the button is clicked, it shows an alert message: "Thanks for clicking!"
Example 2: Binding a Mouseover Handler to a Button
<script type="text/javascript">
function showMessage() {
alert("Ouch! Get off me!");
}
</script>
<form action="#" method="get" name="myForm" id="myForm">
<button id="myButton">Mouse over me!</button>
</form>
<script type="text/javascript">
[Link]("myButton").onmouseover = showMessage;
</script>
- Here, the ‘mouseover’ event for the button is bound to the ‘showMessage’
function.
- When the mouse moves over the button, it triggers the alert: "Ouch! Get off
me!"
Important Considerations
1. Ensure DOM Availability: JavaScript code that binds event handlers should
be executed only after the document elements are fully loaded into the DOM.
If an event handler is set before the element is available, a runtime error will
occur.
Pyq’s question ;
1) Describe Netscape 4 Event Model in detail.
- Netscape 4 introduced the first event model with advanced features that were
not present in the basic event model.
- This model provided greater flexibility in handling events, especially with
respect to where and how events could be handled within the document object
hierarchy.
- However, this model is considered obsolete and is only found in Netscape 4
browsers.
- Since Mozilla-based browsers adopted the DOM2 model and Netscape 6+ was
based on Mozilla, this model is now considered an evolutionary dead end.
- When an event occurs in Netscape 4, the browser creates an ‘Event’ object and
passes it to the handler.
- This event object contains several useful properties that help developers
handle events more efficiently.
1. data: An array of strings containing the URLs of objects that were dragged
and dropped.
3. pageX: The horizontal coordinate where the event occurred (relative to the
page).
4. pageY: The vertical coordinate where the event occurred (relative to the
page).
5. screenX: The horizontal coordinate where the event occurred (relative to the
entire screen).
6. screenY: The vertical coordinate where the event occurred (relative to the
entire screen).
7. target: A reference to the object on which the event occurred (e.g., the
element that was clicked).
9. which: For mouse events, this property indicates which mouse button was used
(1 for left, 2 for middle, 3 for right). For keyboard events, it provides the
numeric (Unicode) value of the key pressed.
- In Netscape 4, the way the ‘Event’ object is passed to the handler is important.
- When the handler is defined as an (X)HTML attribute (like ‘onclick’), the ‘Event’
object is implicitly available within the text of the handler through the ‘event’
identifier.
- For example, in the following code, the x-coordinate of the click is shown using
the ‘screenX’ property of the event:
<a href="[Link]" onclick="alert('Click at ' + [Link]);">Click me!</a>
- However, this ‘event’ object is only accessible within the event handler's
attribute text.
- If you try to use it outside of the event handler's scope (such as in a
JavaScript function), it will not be available, and an error will occur. This is a
common mistake.
-For example, the following code will throw an error because ‘event’ is not
defined in the ‘myHandler’ function:
<script type="text/javascript">
function myHandler() {
alert("Event type: " + [Link]); // Error: event is not defined
}
</script>
<a href="#" onclick="myHandler(); return false;">Click me!</a>
<script type="text/javascript">
function myHandler(event) {
alert("Event type: " + [Link]); // Works fine now
}
</script>
<a href="#" onclick="myHandler(event); return false;">Click me!</a>
- In this corrected version, the ‘event’ object is passed manually to the
‘myHandler’ function, making the event data accessible within the function and
avoiding the error.
Syntax of ‘attachEvent()’
- The ‘attachEvent()’ method allows you to attach an event handler to an object.
The syntax is:
Where:
- The first parameter is a string that specifies the event type (e.g., "onclick").
- The second parameter is the function that should be invoked when the event
occurs.
- You need to pass the exact same arguments (event type and event handler)
that were used when attaching the event.
<!DOCTYPE html>
<html>
<head>
<title>IE Attach/Detach Event Test</title>
<script type="text/javascript">
// Function to show an alert when event occurs
function showAuthor() {
alert("Oscar Wilde");
}
Pyq’s question :
1) Explain DOM2 Event Model.
Event Propagation
In the DOM2 model, events propagate through two main phases:
1. Capture Phase: The event starts from the top (Document) and travels down
through the object hierarchy toward the target. This phase mimics the behavior
found in Netscape 4.
2. Bubbling Phase: After reaching the target element, the event bubbles back
up the hierarchy to the top. This phase is similar to the event model used in
Internet Explorer 4+.
Browser Support
- Mozilla-based browsers (e.g., Mozilla, Firefox, Netscape 6+) were the first to
adopt the DOM2 Event Model.
- Opera 7 and Safari (on macOS) also offer strong support for the DOM2 model.
- Internet Explorer, starting from version 6, does not fully support DOM2
events, creating potential compatibility issues for developers working with
multiple browsers.
1. Multiple Handlers: You can bind several handlers to the same event on an
element. Each handler will be executed when the event occurs, but the order of
execution is arbitrary.
2. Capture Phase Handling: It allows you to handle events during the capture
phase, unlike event handler attributes (e.g., ‘onclick’) that only trigger during the
bubbling phase.
3. Binding to Text Nodes: Prior to DOM2, it wasn’t possible to bind events to
text nodes, but now it is.
#Syntax of ‘addEventListener()’:
[Link]("event", handler, capturePhase);
Where:
- ‘object’: The DOM node to which the event listener is attached.
- ‘"event"‘: A string representing the event type (e.g., "click", "mouseover").
- ‘handler’: The function that will be executed when the event occurs.
- ‘capturePhase’: A Boolean (‘true’ for capture phase, ‘false’ for bubbling phase).
To remove the first handler from the previous example while keeping the
second:
[Link]('myText').removeEventListener("mouseover",
changeColor, true);
Event Objects
- Browsers that support the DOM2 Event Model pass an Event object to event
handlers.
- This object contains additional information about the event that occurred.
- It is similar to the event objects used in proprietary event models, like those
of Netscape and Internet Explorer.
- The properties of the Event object can vary based on the type of event, but
there are some common read-only properties across all event objects.
1. bubbles
- A boolean indicating whether the event bubbles up through the DOM
hierarchy.
2. cancelable
- A boolean indicating whether the event can be canceled.
3. eventPhase
- A numeric value indicating the current phase of event flow.
- 1: Capture phase
- 2: Target phase
- 3: Bubble phase
4. type
- A string that specifies the type of the event (e.g., "click", "keydown").
5. target
- The node to which the event was originally dispatched (i.e., the target of the
event).
6. currentTarget
- The node whose handler is currently executing (i.e., the node the handler is
bound to).
Binding a Handler:
- In the Basic model (Netscape 4), handlers are bound using (X)HTML
attributes.
- In Internet Explorer 4+, handlers can be bound through (X)HTML attributes
or the ‘attachEvent()’ method.
- In the DOM2 model, handlers are bound via (X)HTML attributes or the
‘addEventListener()’ method.
Detaching a Handler:
- In the Basic model (Netscape 4), handlers are detached by setting the
(X)HTML attribute to null via script.
- In Internet Explorer 4+, handlers can be detached using ‘detachEvent()’.
- In the DOM2 model, handlers can be detached using ‘removeEventListener()’.
Event Propagation:
- In the Basic model (Netscape 4), events propagate from the Window down to
the target.
- In Internet Explorer 4+, events propagate from the target up to the
Document.
- In the DOM2 model, events propagate from the Document down to the target
and then back up to the Document.
Stopping Propagation:
- In the Basic and Internet Explorer 4+ models, there is no direct way to stop
propagation.
- In the DOM2 model, propagation can be stopped using the ‘stopPropagation()’
method.
Redirecting an Event:
- In the Basic model (Netscape 4) and Internet Explorer 4+, events cannot be
redirected.
- In the DOM2 model, events can be redirected using the ‘dispatchEvent()’
method.
Decline of Netscape 4:
- The Netscape 4 event model is quickly fading as more browsers adopt the
Mozilla-based browsers and the DOM2 standard.
- Although the DOM2 model is available in many modern browsers, Internet
Explorer's model is still prevalent.
Cross-Browser Compatibility:
- Writing cross-browser event handlers is essential for modern web
development.
- For standard events and simple tasks, writing your own handlers can work.
- For complex tasks, developers may need to rely on or create cross-browser
event libraries.
Some pyq’s important program
Q. Write a JavaScript program to create a Home page of any website and change
background color using.
On mouse over event (mouse over)
On focus event (focus)
- These events allow users to interact with the webpage in a dynamic way, making
the interface more engaging.
1. ‘onmouseover’ Event:
Triggered when the mouse pointer is moved over an HTML element.
Example: Change the background color of the webpage when the user hovers
over a button.
2. ‘onfocus’ Event:
Triggered when an input field gets focused (clicked or tabbed into).
Example: Change the background color of the input field when the user clicks
on it.
Program Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page Example</title>
<style>
/* Styling for the body */
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
Explanation of Code:
1. HTML Structure:
- ‘<h1>‘: Displays the heading of the webpage ("Welcome to My Website").
- Button: A button is added with an ‘onmouseover’ event to change the
background color when the mouse hovers over it.
- Input Field: An input field is added with an ‘onfocus’ event to change the
background color when clicked or tabbed into.
2. CSS Styling:
- Adds styles for the webpage, button, and input field for better presentation.
- Includes hover (‘:hover’) and focus (‘:focus’) pseudo-classes to change button
and input field styles directly.
3. JavaScript Function:
- ‘changeBackgroundColor(color)’: A reusable function to change the
background color of the webpage dynamically.
- The function is triggered on the ‘onmouseover’ and ‘onfocus’ events of the
button and input field, respectively.
Expected Output:
1. Initial State:
- The homepage displays a title, a button, and an input field.
- The background color is white by default.
3. On Input Focus:
- When the user clicks or tabs into the input field, the background color of
the webpage changes to lightpink.
Unit-6 Using JavaScripts
Dialogs :
Pyq’s question :
1) Describe with example the methods alert() and confirm() of Window
object.
A dialog box is a small window in the GUI that appears to request some action
from the user. JavaScript supports three types of dialogs:
1. Alert Dialog
- The ‘alert()’ method of the Window object creates a small window with a
message and an OK button.
- It is used to display simple notifications or debugging messages.
- The alert dialog is modal, meaning the user must dismiss it before interacting
with the rest of the page.
- Syntax:
alert(string);
- Example:
javascript
alert("Hello, World!");
- Note: The message in the alert window can be a string, variable, or the result
of an expression. If a different data type is passed, it will be coerced into a
string.
- Use Case: The alert dialog is typically used for debugging purposes, where
developers want to quickly display messages to users.
2. Confirm Dialog
- The ‘confirm()’ method creates a window with a message and two buttons: OK
and Cancel. The user clicks either to confirm or cancel an action.
- This method is often used to ask the user for confirmation before proceeding
with an operation.
- Syntax:
confirm(string);
- Example:
let isConfirmed = confirm("Do you want to submit the form?");
- Note: In JavaScript, the button labels for the confirm dialog cannot be
customized. It's common to use Yes/No buttons for better usability instead of
OK/Cancel, but the basic method does not support this customization.
3. Prompt Dialog
- The ‘prompt()’ method creates a dialog box that allows the user to enter a
value.
- It is typically used to collect short pieces of data from the user, such as a
name or email address. The dialog includes a text field where the user can type
input.
- Syntax:
var result = prompt(promptString, defaultValueString);
- Example:
let userName = prompt("Please enter your name:", "John Doe");
- Return Value: The ‘prompt()’ method returns the value entered by the user as
a string. If the user cancels the prompt or closes the dialog, it returns ‘null’.
- Note: If only one argument is passed, the second argument is undefined, but
it is advisable to pass an empty string ‘""‘ as a default value if you do not want
the prompt to have a value by default.
- These dialog boxes are useful for gathering simple inputs or providing
messages to users in a web application.
- However, they may disrupt the user experience if overused, as they block
interaction with the rest of the page.
Opening a Window
- The ‘open()’ method is used to open a new browser window with a specified URL,
name, and features.
- You can also set attributes like the window’s size, whether it can be resized,
and whether it has scrollbars.
Syntax:
[Link](url, name, features, replace);
- url: The URL of the document to load into the new window.
- name: The name of the window (used when referencing the window in the
‘target’ attribute of HTML links).
- features: A comma-delimited string that specifies the attributes of the new
window (such as ‘width’, ‘height’, ‘scrollbars’, etc.).
- replace: An optional Boolean value. If ‘true’, the URL will replace the contents
of the current window.
Example:
- In this example, clicking the link opens a new window with the Yahoo website
loaded inside it.
- The window has a height of 300 pixels, a width of 200 pixels, and scrollbars
enabled.
Closing a Window
- Once a window is opened using ‘open()’, you can close it using the ‘close()’
method.
Syntax:
[Link]();
- windowName: The reference to the window object you want to close. This is
usually the variable you assigned when you opened the window (e.g.,
‘secondwindow’).
Example:
<input type="button" value="Close Window" onclick="[Link]();"/>
- In this example, when the button is clicked, the ‘[Link]()’ method
will be called to close the window.
- To safely close a window, you can check if the window object exists before
attempting to close it.
Example:
if (secondwindow) {
[Link]();
}
- This ensures that the ‘close()’ method is called only if the window object is
defined.
Window Features
Pyq’s question :
1) State and explain Window features.
- alwaysRaised:
‘yes/no’
Makes the window always stay on top of other windows.
- dependent:
‘yes/no’
Makes the window dependent on its parent. If the parent window is closed, the
dependent window also closes.
- directories:
‘yes/no’
Controls whether the directories button in the browser's window is shown.
- fullscreen:
‘yes/no’
Makes the window take over the entire screen (only in Internet Explorer).
- height:
Pixel value
Sets the height of the entire window, including the chrome (the window border
and title bar).
- hotkeys:
‘yes/no’
Disables all hotkeys except the essential ones, like quitting, for the new
window.
- innerHeight:
Pixel value
Sets the height of the inner part of the window where the document is
displayed.
- innerWidth:
Pixel value
Sets the width of the inner part of the window where the document is
displayed.
- left:
Pixel value
Specifies the horizontal position of the window from the left side of the
screen.
- location:
‘yes/no’
Controls whether the location bar (URL) is displayed in the window.
- menubar:
‘yes/no’
Specifies whether the browser's menu bar should be shown.
- outerHeight:
Pixel value
Sets the height of the outer part of the window, including the chrome.
- outerWidth:
Pixel value
Sets the width of the outer part of the window, including the chrome.
- resizable:
‘yes/no’
Indicates whether the window can be resized.
- screenx:
Pixel value
Specifies the horizontal distance from the screen's origin to where the window
should open (specific to some browsers like Netscape).
- screeny:
Pixel value
Specifies the vertical distance from the screen's origin for the window's
position.
- scrollbars:
‘yes/no’
Determines if the window should have scrollbars.
- status:
‘yes/no’
Specifies if the status bar at the bottom of the window should be visible.
- titlebar:
‘yes/no’
Specifies if the title bar of the window should be visible.
- toolbar:
‘yes/no’
Specifies if the toolbar should be visible in the new window.
- top:
Pixel value
Specifies the vertical position of the window from the top of the screen
(specific to IE, use ‘screeny’ for cross-browser compatibility).
- width:
Pixel value
Sets the width of the window. It is better to use ‘innerWidth’ for the content
width.
- z-lock:
‘yes/no’
Prevents the window from changing its stacking order relative to other
windows, even if it gains focus.
Example:
javascript
var windowOptions = "directories=no, location=no, width=300, height=300";
var mywindow = open("[Link] "mywindow", windowOptions);
In this example, a new window is opened with the Yahoo website, with specific
options: no directories or location bar, and a window size of 300x300 pixels.
Writing to Windows
- Once a new window is opened, you can use JavaScript to dynamically write
content to it or manipulate its DOM.
- You can use the ‘[Link]()’ or ‘[Link]()’ methods to write
HTML directly into the newly created window.
- The ‘[Link]()’ method is called after writing to finalize the content,
and ‘[Link]()’ brings the window into focus.
[Link]("<html><head><title>fun</title></head><body>");
[Link]("<h1>Hi from JavaScript</h1></body></html>");
- This writes a full HTML document to the newly opened window, including a title
and a header.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript 1.1</title>
<script type="text/javascript">
function customAlert(title, message){
if (jsWindow != null){
jsWindow = [Link]("", "", "width=300, height=200");
var windowHTML = "<html><head><title>" + title + "</title></head>";
windowHTML += "<body bgcolor='black' text='yellow'><h1 align='center'>";
windowHTML += message + "</h1><hr /><div align='center'>";
windowHTML += "<form><input type='button' value='CLOSE'
onclick='[Link]()'>";
windowHTML += "</form></div></body></html>";
[Link](windowHTML);
[Link]();
}
}
function askJS(){
var question = prompt("What is your question?", "");
if (question != null) {
if (question == "")
customAlert("Angry", "You insult me!");
else
customAlert("Bored", "Don't waste my time.");
}
}
</script>
</head>
<body>
<div align="center">
<h1>JavaScript 1.1</h1>
<hr>
<form action="#" method="get">
<input type="button" value="Ask the JS" onclick="askJS();"/>
</form>
</div>
</body>
</html>
- In this example, the ‘askJS()’ function prompts the user for input.
- Based on the input, a custom alert with dynamic content is created and
displayed in a new window.
- If the user doesn't provide any input, a different message is shown.
Pyq’s question :
1) Explain Various methods to control windows and list out window
features.
- JavaScript provides several methods to manipulate windows.
- These methods allow you to control window behavior such as focusing, moving,
resizing, scrolling, and changing the window's location.
1. ‘[Link]()’:
- This method brings a window into focus, making it the active window that the
user can interact with.
- Example: If a window has been opened, you can call this method to bring it
to the front.
2. ‘[Link]()’:
- This method removes focus from the current window, which means the
window will no longer be the active one.
- Example: If you want to shift the focus from a window to another, you would
use ‘[Link]()’.
Moving Windows :
1. ‘[Link](horizontalpixels, verticalpixels)’:
- This method moves the window by a specified number of pixels relative to
its current position.
- Parameters:
- ‘horizontalpixels’: The number of pixels to move the window horizontally
(positive to move right, negative to move left).
- ‘verticalpixels’: The number of pixels to move the window vertically (positive
to move down, negative to move up).
- Example:
javascript
[Link](100, 100);
This moves the window 100 pixels to the right and 100 pixels down.
2. ‘[Link](x-coord, y-coord)’:
- This method moves the window to a specific location on the screen using
exact coordinates.
- Parameters:
- ‘x-coord’: The horizontal coordinate on the screen.
- ‘y-coord’: The vertical coordinate on the screen.
- Example:
javascript
[Link](1, 1);
This moves the window to the top-left corner of the screen (coordinates 1,1).
Resizing Windows
1. ‘[Link](horizontal, vertical)’:
- This method resizes the window by a specified number of pixels in both the
horizontal and vertical directions.
- Parameters:
- ‘horizontal’: The number of pixels to increase or decrease the width of the
window (positive values increase, negative values decrease).
- ‘vertical’: The number of pixels to increase or decrease the height of the
window (positive values increase, negative values decrease).
- Example:
javascript
[Link](10, 10);
2. ‘[Link](width, height)’:
- This method resizes the window to a specified width and height.
- Parameters:
- ‘width’: The width to set for the window in pixels.
- ‘height’: The height to set for the window in pixels.
- Example:
[Link](100, 100);
Scrolling Windows
1. ‘[Link](horizontalpixels, verticalpixels)’:
- This method scrolls the window by a specified number of pixels horizontally
and vertically.
- Parameters:
- ‘horizontalpixels’: The number of pixels to scroll horizontally (positive to
scroll right, negative to scroll left).
- ‘verticalpixels’: The number of pixels to scroll vertically (positive to scroll
down, negative to scroll up).
- Example:
javascript
[Link](10, 0);
2. ‘[Link](x-coord, y-coord)’:
- This method scrolls the window to a specific location, specified by pixel
coordinates.
- Parameters:
- ‘x-coord’: The horizontal pixel position to scroll to.
- ‘y-coord’: The vertical pixel position to scroll to.
- Example:
javascript
[Link](100, 100);
This scrolls the window to position 100 pixels to the right and 100 pixels
down.
3. ‘[Link]()’:
- This is an older method that is similar to ‘scrollBy()’. It is not commonly used
today but still exists for backward compatibility.
By utilizing these methods, you can dynamically control the window’s behavior,
appearance, and location from within JavaScript.
Accessing a Window's History
- JavaScript allows you to interact with a browser's history using the ‘History’
object.
- This object provides methods and properties to navigate through the history
list and manipulate the browser's history.
1. Navigating History:
- The Back and Forward buttons in the browser navigate through the history
list. Similarly, you can use JavaScript to move forward and backward in the
browser's history.
- Example:
<script type="text/javascript">
defaultStatus = 'JavaScript is fun!';
</script>
1. ‘setTimeout()’:
- This method triggers a function or statement after a specified number of
milliseconds.
- Syntax:
timerId = setTimeout(functionToExecute, timeInMilliseconds);
- Example:
<script type="text/javascript">
var timer = setTimeout(function() { alert("Time's up!"); }, 5000); // 5
seconds
</script>
- To cancel the timeout, you use ‘clearTimeout(timerId)’.
2. ‘setInterval()’:
- This method triggers a function at regular intervals, specified in milliseconds.
- Syntax:
timerId = setInterval(functionToExecute, intervalTimeInMilliseconds);
- Example:
<script type="text/javascript">
var timer = setInterval(function() { alert('Are we there yet?'); }, 2000); //
Every 2 seconds
</script>
Window Events
- The ‘Window’ object also supports several events that can be used to respond
to changes in the window's state, such as losing or gaining focus, loading or
unloading the document, and resizing the window.
3. ‘onfocus’:
- Fired when the window gains focus (e.g., when the user returns to the
window).
4. ‘onload’:
- Fired when the document is completely loaded into the window.
5. ‘onresize’:
- Fired when the window is resized.
6. ‘onunload’:
- Fired when the document is unloaded, such as when navigating away from the
current page or closing the window.
These events can be used to handle specific behaviors, such as loading content,
handling errors, or responding to user actions.
Example:
<script type="text/javascript">
[Link] = function() {
alert('The window has been resized!');
};
</script>
- These methods and events provide powerful control over the window and its
behavior, allowing you to create interactive and dynamic web applications.
Extended Window Events
- There are several additional events related to the ‘Window’ object that provide
more control over the window’s behavior.
- These include events that trigger just before or after certain actions occur,
such as printing or unloading the window.
1. ‘onbeforeunload’:
- Triggered just before the window is unloaded, allowing you to display a
confirmation message to the user before they leave the page.
2. ‘onafterprint’:
- Triggered after the window has been printed.
3. ‘onbeforeprint’:
- Fires just before the window is printed or shown in print preview.
4. ‘onhelp’:
- Fires when the Help key (usually F1) is pressed.
5. ‘onresizeend’:
- Triggered when the window resizing has finished (i.e., the user stops dragging
the window’s corner).
6. ‘ondragdrop’:
- Triggered when a document is dragged onto the window (supported by
Netscape only).
7. ‘onresizestart’:
- Fires when the user starts resizing the window (i.e., when dragging the
window's corner begins).
8. ‘onscroll’:
- Triggered whenever the window is scrolled in any direction.
Example:
- In this example, the ‘onload’ event is triggered when the page loads, and the
‘onunload’ event is triggered when the page is being unloaded.
Pyq’s question :
b) What is frame and explain the HTML tags to create frames and how to
change the properties of the frame.
1. Manipulating Frames:
- Each frame in the browser window is accessible through ‘[Link][]’.
This array contains references to each individual frame object in the window.
<!DOCTYPE html>
<html>
<head>
<title>FrameSet Test</title>
</head>
<frameset rows="33%, *, 33%">
<frame src="[Link]" name="frame1" id="frame1" />
<frame src="[Link]" name="frame2" id="frame2" />
<frame src="[Link]" name="frame3" id="frame3" />
</frameset>
</html>
3. Accessing Frames:
- To determine the number of frames in a window:
javascript
[Link]
[Link]
[Link]
[Link]
Inline Frames
- Inline frames (or ‘<iframe>‘) are used to embed another document within a page.
Unlike framesets, inline frames are directly embedded within the document.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Iframe Example</title>
</head>
<body>
<h1>Regular Content here</h1>
<iframe src="[Link] name="ifr1" id="ifr1" height="200"
width="200"></iframe>
<h1>More content here</h1>
</body>
</html>
Applied Frames :
Loading Frames with Links
- You can load content into frames using links, either by specifying the ‘target’
attribute in HTML or by using JavaScript.
Example:
<a href="javascript:[Link]['frame1'].location='[Link]
[Link]['frame2'].location='[Link]
Two sites
</a>
- This method allows you to control the content in multiple frames with a single
action, providing a way to update several parts of a page simultaneously.
Frame Bursting
- Frame busting is a technique used to prevent clickjacking, which occurs when
a malicious website loads a page from another domain into a frame and overlays
it with a counterfeit page.
- This allows the attacker to trick users into interacting with hidden parts of
the original page (like buttons or links) that lead to unintended actions.
- The goal of frame bursting is to ensure that a page is not loaded inside a frame
from another website.
- JavaScript Code for Frame Busting:
function frameBuster() {
if (window != top) {
[Link] = [Link]; // Forces the page to break out of the
frame
}
}
[Link] = frameBuster;
- Explanation: This code checks if the current window is the top-level window
(not inside a frame). If it's inside a frame, it redirects the top window to the
current page’s URL, effectively breaking out of the frame.
Frame Building
- On the other hand, frame building addresses the opposite problem, where a
page might get opened outside of its original frameset.
- For example, users might bookmark a frame within a frameset or launch a link
from a frameset into a new window.
- To avoid this issue, we need to ensure that the document is always viewed
within the context of its original frameset.
if ([Link] == location) {
[Link] = '[Link]'; // Redirects to frameset page if not
in frameset
}
- Explanation: This code checks if the current window is the top window
(‘[Link] == location’).
- If not, it redirects to the frameset page, ensuring the document stays within
the intended frame context.
Form Handling :
Pyqs question :
1) Explain the form handling and the terms form fields, validations,
Dynamic.
- One of the most common uses of JavaScript is for form validation, which allows
you to check the contents of a form before sending it to the server.
- This is crucial for ensuring the data is correct and complete, improving user
experience, and reducing server load.
Form Basics:
- Forms in HTML are accessed through the ‘Form’ object in JavaScript, which is
a part of the ‘Document’ object model (DOM).
- In JavaScript, you can access form elements and validate them before
submission, ensuring that the data is correct and formatted properly before
sending it to the server.
Form Methods:
1. ‘reset()’ method: Clears all form fields (like ‘<input type="reset" />‘).
2. ‘submit()’ method: Submits the form (like ‘<input type="submit" />‘).
3. Event Handlers: ‘onreset’ and ‘onsubmit’ can be used to trigger events when a
form is reset or submitted.
Accessing Forms
Forms can be accessed in several ways:
Example:
Example:
- To refer to the first field in the form:
[Link][0]
Form Elements
HTML supports various form elements including:
Buttons :
There are several types of buttons:
- The submit and reset buttons have default actions, while a generic button
requires a custom event handler.
Text Fields :
2. Password Fields:
<input type="password" />
1. Checkbox:
<input type="checkbox" name="male" id="male" value="male" />
2. Radio Button:
<input type="radio" name="yes" id="yes" value="yes" />
- Both elements allow the user to select options, with checkboxes allowing
multiple selections and radio buttons allowing only one selection within a group.
Hidden Fields
- Hidden fields are used to store state information without rendering on the
page. They are sent along with the form data when submitted.
Syntax:
<input type="hidden" name="user_id" value="12345" />
Syntax:
<input type="file" id="fileupload" name="file" accept="image/png, image/jpeg" />
- The ‘accept’ attribute defines the types of files the user can upload (e.g.,
‘image/png’, ‘application/pdf’).
Select Menus :
- In HTML, the ‘<select>‘ tag is used to create pull-down menus, which can either
allow single or multiple choices.
Example:
<strong>Single Robot Choice:</strong>
<select name="robot" id="robot">
<option>Friend</option>
<option>Cook</option>
<option>Security</option>
<option>Trainer</option>
</select>
Multiple-choice Menu (Scrolled List)
This allows the user to select more than one option from the list. It is created
by adding the ‘multiple’ attribute.
Example:
<strong>Multiple Robot Choice:</strong>
<select name="robotMulti" id="robotMulti" size="4" multiple="multiple">
<option>Security</option>
<option>Trainer</option>
<option>Friend</option>
<option>Cook</option>
</select>
Option Elements :
The ‘<option>‘ elements define the choices in a ‘<select>‘ menu. Each ‘<option>‘ can
have different properties:
Option Groups :
- You can group related options within a ‘<select>‘ menu using the ‘<optgroup>‘ tag.
This allows for better organization and visual separation of choices.
Example:
<select name="robotchooser" id="robotchooser">
<option>Choose your robot</option>
<option>----</option>
<option>Butler</option>
<optgroup label="Security Models">
<option>Man</option>
<option>K-9</option>
</optgroup>
<option>Female</option>
<optgroup label="Friend Models">
<option>Male</option>
</optgroup>
<option>Trainer</option>
</select>
Output:
- Choose your robot
- Butler
- Security Models
- Man
- K-9
- Female
- Friend Models
- Male
- Trainer
The ‘<optgroup>‘ tag creates labeled groups within the dropdown, helping
organize the options.
Example:
<label>Username:
<input type="text" id="username" name="username" />
</label>
<label for="userpassword">Password:</label>
<input type="password" id="userpassword" name="userpassword" />
The ‘for’ attribute in ‘<label>‘ is used to link the label to a specific input element
by matching the input's ‘id’.
Example:
Validation Process
- Before they happen: Prevent errors before the user enters data.
- As they happen: Check and display errors as users fill in the form.
- After they happen: Check form data before submission.
- Typically, form validation is done just before submission, where if any errors
are found, they are displayed, and the form submission is canceled by returning
‘false’ in the event handler.
var validations = [
["[Link]", "notblank"],
["[Link]", "validemail"],
["[Link]", "isnumber"]
];
switch (checkToMake) {
case 'notblank':
if (isEmpty([Link])) {
alert("Field may not be empty");
[Link]();
return false;
break;
case 'validemail':
if (!looksLikeEmail(field)) return false;
break;
case 'isnumber':
if (!isInteger(field)) return false;
break;
}
return true;
}
function isInteger(field) {
// logic for checking integer
}
function looksLikeEmail(field) {
// logic for checking email format
}
function isEmpty(s) {
return !s || [Link]() === "";
}
- In this way, you can easily validate different forms with different field
requirements by adjusting the validation array.
- This modular approach improves maintainability and reusability.
- A dynamic form can be used to calculate values like subtotals, tax, shipping
cost, and grand total as the user interacts with the form.
- The form shown here calculates the total costs based on quantities of items
entered by the user.
- JavaScript is used to perform calculations and update fields in real time.
<body>
<!-- Form structure -->
<form id="myform" name="myform" action="#" method="get">
<!-- Input fields for item quantities and their total costs -->
Widgets:
<input type="text" name="widgets" id="widgets" size="2" value="0"
onchange="calc();" onkeypress="return isNumberInput(this, event);" />
@1.50 each
<input type="text" id="widgettotal" name="widgettotal" size="5"
readonly="readonly" />
<br />
Gadgets:
<input type="text" name="gadgets" id="gadgets" size="2" value="0"
onchange="calc();" onkeypress="return isNumberInput(this, event);" />
@2.70 each
<input type="text" id="gadgettotal" name="gadgettotal" size="5"
readonly="readonly" />
<br />
Thingies:
<input type="text" name="thingies" id="thingies" size="2" value="0"
onchange="calc();" onkeypress="return isNumberInput(this, event);" />
@1.25 each
<input type="text" id="thingietotal" name="thingietotal" size="5"
readonly="readonly" />
<br /><br /><br />
<em>Shipping:</em>
Next day:
<input type="radio" value="12.00" name="shipping" id="shipping"
checked="true" onclick="calc();" />
2-day:
<input type="radio" value="7.00" name="shipping" id="shipping"
onclick="calc();" />
Standard:
<input type="radio" value="3.00" name="shipping" id="shipping"
onclick="calc();" />
<br /><br /><br />
<strong>Grand Total:</strong>
<input type="text" id="grandtotal" name="grandtotal" size="8"
readonly="readonly" />
</form>
</body>
</html>
Detailed Explanation of the Code
1. Form Structure:
- The form contains input fields for entering quantities of "widgets,"
"gadgets," and "thingies," and displays their total costs.
- The user can select a shipping option (Next day, 2-day, or Standard), and
the corresponding shipping cost is applied.
2. JavaScript Functions:
- ‘isNumberInput’: Ensures that only numeric values are entered in the
quantity fields. It blocks any non-numeric characters.
- ‘format’: Rounds the calculated values to two decimal places to represent
money values correctly.
- ‘calc’: This is the main function that performs the calculations:
- It calculates the total cost for each item (widget, gadget, thingie) by
multiplying the quantity by the item cost.
- It calculates the subtotal by summing the individual totals.
- It applies tax by multiplying the subtotal by the tax rate.
- It determines the shipping cost based on the selected shipping option.
- It calculates the grand total by adding the subtotal, tax, and shipping
cost.
3. Event Handling:
- ‘onchange’: Each input field triggers the ‘calc’ function when the value is
changed, updating the totals dynamically.
- ‘onkeypress’: This event restricts input to numeric characters only, ensuring
no invalid characters are entered.
4. Dynamic Calculation:
- As the user updates the quantities or selects different shipping options, the
form automatically recalculates the total values (subtotal, tax, shipping, grand
total) without needing to reload the page.
Key Points to Remember:
Key Features:
1. Form Inputs:
- Name, Address, City, State, Gender, Mobile Number, and Email ID fields are
created.
2. Validation Rules:
- Name Validation: Only letters are allowed.
- Mobile Number Validation: Must contain exactly 10 digits.
- Email Validation: Checks for a valid email format (e.g., user@[Link]).
3. Error Messages:
- Displays alerts for invalid input values.
Program Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Information Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 0;
}
h1 {
text-align: center;
color: #333;
}
form {
width: 50%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input, select {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}
.gender {
width: auto;
margin-right: 10px;
}
button {
background-color: #007BFF;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.error {
color: red;
font-size: 14px;
}
</style>
</head>
<body>
<h1>Student Information Form</h1>
<label for="address">Address:</label>
<input type="text" id="address" placeholder="Enter your address">
<label for="city">City:</label>
<input type="text" id="city" placeholder="Enter your city">
<label for="state">State:</label>
<input type="text" id="state" placeholder="Enter your state">
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="Male" class="gender">
Male
<input type="radio" id="female" name="gender" value="Female"
class="gender"> Female
<button type="submit">Submit</button>
</form>
<script>
// Function to validate form inputs
function validateForm() {
// Get form inputs
const name = [Link]("name").[Link]();
const mobile = [Link]("mobile").[Link]();
const email = [Link]("email").[Link]();
Explanation of Code:
1. HTML Form:
- Includes input fields for Name, Address, City, State, Gender, Mobile
Number, and Email ID.
- Uses ‘<form>‘ to wrap the inputs and specify the onsubmit attribute for
validation.
2. CSS Styling:
- Provides a visually appealing layout with labels, input fields, and a submit
button.
- Input fields and button styles are customized for better readability and user
interaction.
3. JavaScript Validation:
- Validates each input using regular expressions.
- Name Validation: Ensures only letters are allowed.
- Mobile Validation: Checks for a 10-digit number.
- Email Validation: Verifies the format of the email address.
- Displays alerts for incorrect inputs to guide the user.
Expected Output:
1. Initial View:
- A form with fields for Name, Address, City, State, Gender, Mobile Number,
and Email ID appears.
2. Validations:
- Entering invalid inputs (e.g., numbers in the name, less than 10 digits for
mobile, or an incorrect email format) triggers appropriate error messages.
3. Successful Submission:
- Displays "Form submitted successfully!" if all inputs are valid.
Design and implement a simple calculator using Java script for operations like
addition, multiplication, subtraction, division, square of a number.
Objective:
To create a simple calculator that performs the following operations:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square of a Number
Program Overview:
1. User Interface:
The calculator has buttons for numbers (0-9) and operations (+, -, ×, ÷, and
square).
2. Functionalities:
- Takes two input values for operations like addition, subtraction,
multiplication, and division.
- Calculates the square of a number when the "Square" button is pressed.
3. Output Display:
Displays the result dynamically on the screen.
Program Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}
h1 {
margin-top: 20px;
color: #333;
}
.calculator {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 2px solid #ccc;
border-radius: 10px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}
input[type="number"], .result {
width: 90%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
button {
padding: 10px 20px;
margin: 5px;
border: none;
background-color: #007BFF;
color: white;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>Simple Calculator</h1>
<div class="calculator">
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<div class="result" id="result">Result: </div>
<button onclick="performOperation('add')">Add</button>
<button onclick="performOperation('subtract')">Subtract</button>
<button onclick="performOperation('multiply')">Multiply</button>
<button onclick="performOperation('divide')">Divide</button>
<button onclick="performSquare()">Square</button>
</div>
<script>
function performOperation(operation) {
// Get input values
const num1 = parseFloat([Link]("num1").value);
const num2 = parseFloat([Link]("num2").value);
let result;
function performSquare() {
// Get the first input value
const num1 = parseFloat([Link]("num1").value);
Explanation of Code:
HTML:
- Input Fields:
Two fields (‘id="num1"‘ and ‘id="num2"‘) allow users to enter numbers.
- Buttons:
Buttons trigger different operations (addition, subtraction, multiplication,
division, and square).
CSS:
- Calculator Styling:
The calculator is styled for a clean and user-friendly interface with proper
alignment and colors.
JavaScript:
1. ‘performOperation(operation)’ Function:
- Handles addition, subtraction, multiplication, and division based on the input
parameter (‘operation’).
- Validates inputs and prevents division by zero.
2. ‘performSquare()’ Function:
- Calculates the square of the first input value (‘num1’).
Output:
Initial View:
- Displays input fields for two numbers and buttons for operations.
Operations:
1. Addition: Outputs the sum of two numbers.
2. Subtraction: Outputs the difference of two numbers.
3. Multiplication: Outputs the product of two numbers.
4. Division: Outputs the quotient of two numbers (displays an error for division
by zero).
5. Square: Outputs the square of the first input value.
Result Display:
Results are shown dynamically in the "Result" section.
All The Best !!!