0% found this document useful (0 votes)
9 views

Unit_4 (1)

The document outlines the syllabus for a UI Web Development course, focusing on JavaScript concepts including functions, arrays, strings, and the Document Object Model (DOM). It explains how to create and manipulate arrays and strings, as well as the use of various JavaScript methods and functions. Additionally, it covers event handling and form validation within the context of web development.

Uploaded by

sirdin8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit_4 (1)

The document outlines the syllabus for a UI Web Development course, focusing on JavaScript concepts including functions, arrays, strings, and the Document Object Model (DOM). It explains how to create and manipulate arrays and strings, as well as the use of various JavaScript methods and functions. Additionally, it covers event handling and form validation within the context of web development.

Uploaded by

sirdin8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

MR24-1CS0102

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.

There are three ways to create an array in JavaScript. They are:


 By array literal
 By creating instance of Array directly (using new keyword)
 Using an Array constructor (using new keyword)

MR24-1CS0102 UI Web Development


1
JavaScript Array literal
Array literal is the most common and easiest way to create an array in JavaScript.
Syntax
var arrayname = [value0, value1, value2, value3, ..... valueN];

Example
<html>
<head>
<title>JavaScript Arrays</title>
<script>
let person = [“Sachin", “ Dravid", " Rohit", “ Kohli”]; document.write(person);
// Accessing full array.
</script>
</head>
</html>

Creating Array directly using new keyword/ Empty constructor


 Arrays in JavaScript are simple objects, so another way to create an array in JavaScript is by
directly creating an instance of an object. let arrayname = new Array();
Example
<html>
<head>
<title>JavaScript Arrays</title>
<script> // Creating an array using new keyword.
let nums = new Array();
nums[0] = 10;
nums[1] = "John";
nums[2] = 30;
nums[3] = 50;
nums[4] = true;
document.write(nums);
</script>
</head>
</html>

Using an Array constructor (using new keyword)


The Array() constructor creates Array objects. You can declare an array with the "new"
keyword to instantiate the array in memory.

MR24-1CS0102 UI Web Development


2
Example
<script>
Var arr1=new Array(“AIML",“CSE",“DS");
for (i=0;i<arr1.length;i++){
document.write(arr1[i] + "<br>");
}
</script>

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);

MR24-1CS0102 UI Web Development


3
</script>

</body>
</html>
Output:

JAVASCRIPT Array METHODS


1. JavaScript Array length
Returns the number of elements in an array
let city = [“Hyderabad", “Ramanthapur", “Secunderabad"];
let len = city.length;
console.log(len);
2. JavaScript Array reverse()
Returns the array in reverse order
let numbers = [1, 2, 3, 4, 5];
let result= numbers.reverse();
console.log(result);
3. JavaScript Array sort()
Sorts the elements of an array in specific order

MR24-1CS0102 UI Web Development


4
let city = [“Hyderabad", “Ramanthapur", “Secunderabad"];
let result = city.sort();
console.log(result);
4. JavaScript Array toSort()
Returns a string with elements of the array separated by commas
let items = ["JavaScript", 1, "a", 3];
let result = items.toString();
console.log(result);
5. JavaScript Array pop()
Removes and returns the last array element
let cities = [“Hyderabad", “Ramanthapur", “Secunderabad"];
let result= cities.pop();
console.log(cities);
console.log(result);
6. JavaScript Array push()
Adds elements to end of array & returns its length
let city = [“Hyderabad", “Ramanthapur", “Secunderabad"]; city.push(“Bangalore");
console.log(city);

JAVASCRIPT ARRAY METHODS EXAMPLE

<!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> Reverse of the array is: ");


let rev = a.reverse();

MR24-1CS0102 UI Web Development


5
document.write(rev);

document.write("<br> array after sorting is: ");


document.write(a.sort());

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

MR24-1CS0102 UI Web Development


6
ways you can use quotes.
 Single quotes: 'Hello'
 Double quotes: "Hello"
 Backticks: `Hello`

objects, using the String() constructor:


const string4 = new String("A String object");
const name = ‘Ram';
const name1 = “Sita";
const result = `The names are ${name} and ${name1}`;
Backticks are generally used when you need to include variables or expressions into a string.
This is done by wrapping variables or expressions with ${variable or expression} as shown
above.
You can also write a quote inside another quote. For example,
const name = 'My name is “Ram".';
However, the quote should not match the surrounding quotes. For example,
const name = 'My name is ‘Ram'.'; // error
JAVASCRIPT STRING METHODS
1. concat()
joins two or more strings
2. toUpperCase()
returns the passed string in upper case
3. trim()
removes whitespace from the strings
4. split()
converts the string to an array of strings
5. slice(start, end)
returns a part of a string

Example for string methods

<!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>

MR24-1CS0102 UI Web Development


7
<h1> String in JS</h1>

<body>
<script>

let s1 = "Apple", s2 = new String("banana");


if (s1 == s2) {
console.log("Strings " + s1 + " and " + s2 + " are equal");
}
else {
console.log("Strings " + s1 + " and " + s2 + " are not equal");
}
console.log("String compare s1.localeCompare(s2)", s1.localeCompare(s2));
console.log("Concatenate s1.concat(s2):", s1.concat(s2));
console.log("Concatenate (s1+s2):", (s1+s2));
console.log("s1.chatAt(3)", s1.charAt(3));
console.log("s1.substring(1,3):", s1.substring(1,3));
console.log("s1.substr(1,3):", s1.substr(1,3));
console.log("s1.slice(2,4)", s1.slice(2,4));
console.log("s1.toUpperCase", s1.toUpperCase());
console.log("s2.toLowerCase", s2.toLowerCase());
</script>

</body>

</html>

Output:

MR24-1CS0102 UI Web Development


8
JAVASCRIPT FUNCTIONS

A function (also known as a method) is a self-contained piece of code that performs a


particular "function". You can recognise a function by its format - it's a piece of descriptive
text, followed by open and close brackets.A function is a reusable code-block that will be
executed by an event, or when the function is called.

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:

MR24-1CS0102 UI Web Development


9
Function parameters are the names listed in the function definition. The parameter rules are
listed below:
 Formal Parameter : Parameter Written in Function Definition is Called Formal
Parameter.
 Actual Parameter : Parameter Written in Function Call is Called “Actual Parameter”
 The function that calls the subroutine is called the caller
 The function that gets called(i.e. subroutine) by the caller is called the callee

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>

MR24-1CS0102 UI Web Development


10
<input type="button" value="Click
me!" onclick="displaymessage()" >
</form>
</body>
</html>

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.

HOW TO DEFINE A FUNCTION

The syntax for creating a function is:


function functionname(var1,var2,...,varX)
{
some code
}

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
}

MR24-1CS0102 UI Web Development


11
Note: Do not forget about the importance of capitals in JavaScript! The word function
must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that
you must call a function with the exact same capitals as in the function name.

The return Statement

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.

JavaScript program to find factorial of a number


Logic to find factorial of the number
 Declared fact variable with initialization value 1.
 Take a number from the user and store it in a variable a.
 Iterate the loop from 1 to user value i.e a,
 inside the loop calculate the factorial of a given number by using code fact=fact*i;
 when the loop breaks factorial value will get stored in a fact variable, after the loop end print
the factorial value.
<!DOCTYPE html>
<html>
<body>
<script>
function factorial()
{
var fact=1,i;
var a=prompt("enter a number:");

MR24-1CS0102 UI Web Development


12
for(i=1;i<=a;i++)
{
fact=fact*i;
}
document.write("factorial of number "+a+" is:",fact);
}
</script>
<form>
<input type="button" value="factorial" onclick="factorial();">
</form>
</body>
</html>

APPLY METHOD IN FUNCTIONS

 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.

MR24-1CS0102 UI Web Development


13
DOM (DOCUMENT OBJECT MODEL)

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’);

• getElementsByClassName: This method returns a collection of all elements with a given


class name.
o const elements = document.getElementsByClassName('myClassName’);

• getElementsByTagName: This method returns a collection of all elements with a given


tag name.

MR24-1CS0102 UI Web Development


14
o const elements = document.getElementsByTagName('div');
• querySelector: This method returns the first element that matches a specified CSS
selector.
o const element = document.querySelector('.myClassName’);

• 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!";

MANIPULATING HTML AND CSS VIA JAVASCRIPT.

• innerHTML
• querySelector
• createElement
• appendChild
• removeChild
• HTMLElement.style
• setAttribute
Changing HTML Content
You can change the content of an HTML element using the innerHTML property:

<p id="demo">This is a paragraph.</p>


<script>
document.getElementById("demo").innerHTML = "Hello, World!";
</script>

Modifying CSS Styles


To change the style of an HTML element, use the style property:
document.getElementById(id).style.property = new style

<p id="demo">This is a paragraph.</p>


<script>
document.getElementById("demo").style.color = "blue";
</script>

Adding and Removing Elements


You can add new elements to the DOM or remove existing ones:

MR24-1CS0102 UI Web Development


15
<div id="container"></div>
<script>
// Create a new element
var newElement = document.createElement("p");
newElement.innerHTML = "This is a new paragraph.";

// Append the new element to the container


document.getElementById("container").appendChild(newElement);

// 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

MR24-1CS0102 UI Web Development


16
<!DOCTYPE html>
<html lang="en">

<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 (BUBBLING VS. CAPTURING)

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.

MR24-1CS0102 UI Web Development


17
Handled by default when adding an event listener without { capture: true }.

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.

FORMS AND FORM VALIDATION:


WORKING WITH FORMS
Form validation in JavaScript is a crucial aspect of web development, ensuring that user inputs
are correct and useful before they are submitted to the server.
Examples:
• This field is required" (You can't leave this field blank).
• "Please enter your phone number in the format xxx-xxxx" (A specific data format is
required for it to be considered valid).
• "Please enter a valid email address" (the data you entered is not in the right format).
"Your password needs to be between 8 and 30 characters long and contain one uppercase
letter, one symbol, and a number." (A very specific data format is required for your data).
Working with forms and form validation in JavaScript is essential for creating interactive and
user-friendly web applications

When we validate a form in JavaScript, we typically follow these steps:


Data Retrieval:The first step is to get the user’s values entered into the form fields (like name,
email, password, etc.).
Data Validation:
 Name Validation: We check to make sure the name field isn’t empty and doesn’t contain
any numbers.
 Email Validation: We make sure that the email field isn’t empty and that it includes the
“@” symbol.
 Password Validation: We ensure that the password field isn’t empty and that the
password is at least 6 characters long.

Error Handling:

MR24-1CS0102 UI Web Development


18
If any of the checks fail, an alert message is shown to the user using telling them what’s
wrong.
Submission Control:
If all the validation checks pass, the function returns true, meaning the form can be
submitted. If not, it returns false, stopping the form from being submitted.
Focus Adjustment:
The form automatically focuses on the first field that has an error, guiding the user to fix it.
handling form submissions

HANDLING FORM SUBMISSIONS

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>

MR24-1CS0102 UI Web Development


19
</form>

</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');

// Add event listener to the form


form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent default form submission for validation

// Basic email validation without regex


const email = emailInput.value;
const name= nameInput.value

if (name === "" )


{
alert("Name field cant be empty .");
}
else if (!email.includes('@') || email === ""|| (email.indexOf('.') <= email.indexOf('@') +
1)) {
alert("Please enter a valid email address.");
}
else {
alert("Form submitted successfully!");
form.submit(); // Manually submit the form after validation
}
});

MR24-1CS0102 UI Web Development


20
CLIENT-SIDE FORM VALIDATION
Validation done in the browser is called client-side validation, while validation done on the
server is called server-side validation.
Client-side validation is an initial check, by catching invalid data on the client-side, the user
can fix it straight away.
Your apps should always perform validation, including security checks, on any form-
submitted data on the server-side as well as the client-side, because client-side validation is
too easy to bypass, so malicious users can still easily send bad data through to your server.
Two different types of client-side validation
 HTML form validation HTML form attributes can define which form controls are
required and which format the user-entered data must be in to be valid.
 JavaScript form validation JavaScript is generally included to enhance or customize
HTML form validation.
Built-in form validation attributes
 The required attribute: Add this attribute to an input to make an element
mandatory.
 minlength and maxlength: Specifies the minimum and maximum length of textual
data (strings).
 min, max: Specifies the minimum and maximum values of numerical input types,
Validating against a regular expression Using the pattern attribute
a — Matches one character that is a (not b, not aa, and so on).
abc — Matches a, followed by b, followed by c.
b*- zero or more
b+ - one or more
ab?c — Matches a, optionally followed by a single b, followed by c. (ac or abc)
ab*c — Matches a, optionally followed by any number of bs, followed by c. (ac, abc,
abbbbbc, and so on).
a|b — Matches one character that is a or b.

Regular expression for email:


/^[a-zA-Z0-9._-]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$/.test(email))

 /^: match must begin at the start of the string.


 [a-zA-Z0-9._-]+: more than one occurance of a-z,A-Z,0-9,.,_,-.
 @
 \.: escape character of . This seperates domain name and its extension Eg gmail.com
 ]{2,} 2 letter or more
 $: ensures that there are no extra characters after the domain extension.

MR24-1CS0102 UI Web Development


21
 test(email): checks the correctness of the regular expression

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');

MR24-1CS0102 UI Web Development


22
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
const errorMessage = document.getElementById('error-message'); // Access the error
message span

// Add event listener to the form


form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent default form submission for validation

// Clear previous error messages


errorMessage.textContent = '';

// Basic email validation without regex


const email = emailInput.value;
const name = nameInput.value;

if (name === "") {


errorMessage.textContent = "Name field can't be empty.";
} else if (!isValidEmail(email)) {
errorMessage.textContent = "Please enter a valid email address.";
} else {
alert("Form submitted successfully!");
form.submit(); // Manually submit the form after validation
}
});

// Function to validate email format using regex


function isValidEmail(email) {
return (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email));
}

MR24-1CS0102 UI Web Development


23

You might also like