Unit_4 (1)
Unit_4 (1)
UI Web Development
B. Tech I Year– I Semester
Unit 4
Syllabus
JavaScript II: Functions: Definition, Parameters, Invocation, function call and apply (), Arrays and
strings.
DOM (Document Object Model): Understanding the DOM, accessing elements, manipulating
HTML and CSS via JavaScript. Events: Event handling, event listeners (addEventListener), event
propagation (bubbling vs. capturing). Forms and Form Validation: Working with forms, handling
form submissions, client-side form validation
ARRAYS
An array in JavaScript is an ordered set of data (or values) represented by a single variable
name. JavaScript arrays are resizable/Dynamic. It is Heterogeneous- can contain a mix of
different data types. JavaScript arrays are zero-indexed. Array Length Accessed via array.length.
Array uses a single variable name to store more than one value.
Arrays are not stored in contiguous memory due to their dynamic nature and the ability to hold
multiple data types.
Example
<html>
<head>
<title>JavaScript Arrays</title>
<script>
let person = [“Sachin", “ Dravid", " Rohit", “ Kohli”]; document.write(person);
// Accessing full array.
</script>
</head>
</html>
Example-1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arrays</title>
</head>
<body>
<h2> Arrays In JS</h2>
<script>
let person = ["Sachin","Dravid"," Rohit", "Kohli"];
document.write(person);
document.write(" <br>Arrays in JS are heterogeneous<br>");
let arr=new Array();
arr[1]=10;
arr[2]="apple";
arr[0]=3.5;
arr[3]=null;
document.write(arr);
document.write("<br> Displaying using for loop<br>");
for(i=0;i<arr.length;i++)
document.write(arr[i],"<br>");
document.write("<br> Array created using constructor<br>");
let a=new Array(1,"apple", 9.23, true);
for(i=0;i<a.length;i++)
document.write(a[i],"<br>");
document.write(a);
</body>
</html>
Output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Methods</title>
</head>
<body>
<h1> Array Methods </h1>
<script>
let a = new Array(1, "apple", 9.23, true, 2, "pear", 3.23, false, null);
let len = a.length;
document.write("<br> Length of the array is ", len);
document.write("<br> Array.push()<br>");
a.push("hyd");
document.write(a);
document.write("<br> Array.pop()<br>");
let e = a.pop();
document.write(a, "<br>popped element:", e);
document.write("<br> Array.shift<br>");
let d = a.shift();
document.write(a, "<br> element removed: ", d);
</script>
</body>
</html>
Output:
JAVASCRIPT STRING:
JavaScript string is a primitive data type that is used to work with texts.
Example: const name = 'John';
CREATE JAVASCRIPT STRINGS
In JavaScript, strings are created by surrounding them with quotes. There are three
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
</body>
</html>
Output:
To keep the browser from executing a script when the page loads, you can put your script
into a function. A function contains code that will be executed by an event or by a call to
that function.
You may call a function from anywhere within the page (or even from other pages if the
function is embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document.
However, to assure that the function is read/loaded by the browser before it is called, it
could be wise to put it in the
<head> section.
FUNCTION PARAMETERS:
FUNCTION INVOCATION:
The code inside a function is not executed when the function is defined.The code inside a
function is executed when the function is invoked.It is common to use the term "call a
function" instead of "invoke a function".
FUNCTION CALL:
The Javascript Function call is a predefined javascript method, that is used to write methods
for different objects. The keyword this refers to the “owner” of the function or the object it
belongs to.
Example
<html>
<head>
<script
type="text/javascript">
function
displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
If the line: alert("Hello world!!") in the example above had not been put within a function,
it would have been executed as soon as the line was loaded. Now, the script is not
executed before the user hits the button. We have added an onClick event to the button
that will execute the function displaymessage() when the button is clicked.
You will learn more about JavaScript events in the JS Events chapter.
var1, var2, etc are variables or values passed into the function. The { and the } defines the
start and end of the function.
Note: A function with no parameters must include the parentheses () after the function
name:
function functionname()
{
some code
}
The return statement is used to specify the value that is returned from the function. So,
functions that are going to return a value must use the return statement.
Example
The function below should return the product of two numbers (a and b):
function prod(a,b){
x=a*b;
return x;
}
When you call the function above, you must pass along two parameters:
product=prod(2,3);
The returned value from the prod() function is 6, and it will be stored in the variable called
product.
apply()
The apply() method of Function instances calls this function with a given this value, and
arguments provided as an array
It writes a method that can be used on different objects.
It returns the method values of a given function
The apply() method takes arguments as an array.
EXAMPLE CODE:
function sum(a, b) {
return a + b;
}
var numbers = [5, 10];
var result = sum.apply(null, numbers);
console.log(result); //
OUTPUT: 15
NOTE: The first argument of `apply()` is set to `null` because we don't need to set a specific
context for the `sum` function.
The Document Object Model (DOM) connects web pages to scripts or programming languages
by representing the structure of a document—such as the HTML representing a web page—in
memory.
The DOM represents a document with a logical tree.
HTML Elements as Objects: The DOM treats HTML elements as objects, with properties,
methods, and events.Manipulation: JavaScript can use the DOM to change all HTML elements,
attributes, and CSS styles on a page. It can also add or remove elements and attributes.
Each branch of the tree ends in a node, and each node contains objects.DOM methods allow
programmatic access to the tree. With them, you can change the document's structure, style, or
content.Document Object Model (DOM) representation allows it to be manipulated
HTML DOM methods are actions you can perform (on HTML Elements).HTML DOM properties
are values (of HTML Elements) that you can set or change.
ACCESSING ELEMENTS
common methods to access elements using JavaScript:
• getElementById: This method retrieves an element by its unique ID.
o const element = document.getElementById(‘one’);
• The innerHTML property is useful for getting or replacing the content of HTML
elements.
document.getElementById("demo").innerHTML = "This is a new value inserted into a
document!";
• innerHTML
• querySelector
• createElement
• appendChild
• removeChild
• HTMLElement.style
• setAttribute
Changing HTML Content
You can change the content of an HTML element using the innerHTML property:
// Remove an element
var elementToRemove = document.getElementById("demo");
elementToRemove.parentNode.removeChild(elementToRemove);
</script>
EVENTS
Events are things that happen in the system you are programming — the system produces a
signal when an event occurs, and provides a mechanism by which an action can be
automatically taken
An event represents a change in the state of an object or a specific action performed by the
user, such as clicking a button, pressing a key, or moving the mouse
The user selects, clicks, or hovers the cursor over a certain element.
The user chooses a key on the keyboard.
The user resizes or closes the browser window.
A web page finishes loading.
A form is submitted.
A video is played, paused, or ends.
An error occurs.
Events
To react to an event, you attach an event handler/event listeners to it.
event handler/event listeners is a block of code (usually a JavaScript function) that runs when
the event fires. When such a block of code is defined to run in response to an event, we say we
are registering an event handler
The listener listens out for the event happening, and the handler is the code that is run in
response to it happening
Example: Change background color of button and body when a button is clicked
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Color</title>
</head>
<body>
<button id="colorButton">Change Background Color</button>
<script>
document.getElementById('colorButton').addEventListener('click', function () {
document.body.style.backgroundColor = 'lightblue';
colorButton.style.backgroundColor = "green";
});
</script>
</body>
</html>
Event propagation
Event propagation in JavaScript refers to the way events travel through the DOM (Document
Object Model) tree. There are two main phases of event propagation: bubbling and capturing.
Event Bubbling
Definition: In event bubbling, the event starts from the target element and bubbles up to the
root of the DOM tree.
When an event occurs on an element, it first triggers the handlers on that element, then on its
parent, and so on, up to the root.
Use Case: Bubbling is useful when you want to handle events at a higher level in the DOM
hierarchy.
For example, you can attach a single event handler to a parent element to manage events for all
its children.
Event Capturing(Trickling)
Definition: In event capturing, the event starts from the root and travels down to the target
element.
The event first triggers the handlers on the root element, then on its children, and so on,
down to the target element.
Use Case: Capturing is useful when you need to handle events before they reach the target
element. This can be important for tasks like validation or logging.
Enabled by setting { capture: true } in addEventListener.
Error Handling:
Example: Create an HTML form containing input fields for name and email, and a submit
button. validate that the email input for a valid email format. Display an alert message if the
form is valid or if there are validation errors
Form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="formvalidation.js" defer></script>
</head>
<body>
<h2>Contact Form</h2>
<form action="/submit-form" method="post" id="registrationForm" >
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" >
</div>
<br>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" >
</div>
<br>
<button type="submit">Submit</button>
</body>
</html>
formvalidation.js
// Access form elements by their IDs
const form = document.getElementById('registrationForm');
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
Example: Create an HTML form containing input fields for name and email, and a submit
button. validate that the email input for a valid email format using regular expressions.
Display an error message if the form is invalid
FormSpan.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
<script src="FormSpan.js" defer></script>
</head>
<body>
<h2>Contact Form</h2>
<form action="/submit-form" method="post" id="registrationForm">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</div>
<br>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</div>
<br>
<span id="error-message" style="color: red;"></span> <!-- Span for error messages -->
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>
FormSpan.js
// Access form elements by their IDs
const form = document.getElementById('registrationForm');