0% found this document useful (0 votes)
64 views60 pages

E-Note 28408 Content Document 20241129053919PM

complete ppt

Uploaded by

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

E-Note 28408 Content Document 20241129053919PM

complete ppt

Uploaded by

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

Dayananda Sagar University

School of Engineering
Devarakaggalahalli, Harohalli Kanakapura Road, Dt, Ramanagara, Karnataka 562112

Department of Computer Science & Engineering


(Artificial Intelligence & Machine Learning)

SEC-III WEB DEVELOPMENT


SEMESTER – V
Unit-4
Syllabus
UNIT – IV
JavaScript and JQuery:
 Basics of JavaScript and Client-side scripting language.
 JavaScript syntaxes for variables, functions, branches and repetitions.
 JavaScript alert, prompt and confirm.
 Objects in JavaScript, Access/Manipulate web browser elements using DOM
Structure, forms and validations, JavaScript events.

29-11-2024 Prepared by : Dr. M. Lakshmanan 2


JavaScript Name
Origins with Mocha and LiveScript:
When Brendan Eich developed the language at Netscape in 1995, it was originally called
Mocha. Shortly after, it was renamed LiveScript, as it was intended to make webpages
more interactive.
Collaboration with Sun Microsystems:
Netscape entered a partnership with Sun Microsystems, the developers of the Java
programming language. At the time, Java was gaining significant attention and popularity.
Marketing Strategy:
To ride on the wave of Java’s success and increase adoption, Netscape rebranded
LiveScript to JavaScript. This was primarily a marketing move and not because of any
technical similarity or connection to Java

29-11-2024 Prepared by : Dr. M. Lakshmanan 3


Basics of JavaScript
 JavaScript is a high-level, interpreted programming language primarily used to create
interactive and dynamic content on websites. It enables developers to build web
applications, control multimedia, animate images, and much more.
 JavaScript is the most popular scripting language on the Internet, and works in all major
browsers, such as Internet Explorer, Mozilla Firefox, and Opera.
Key Features of JavaScript:
 Client-Side Scripting: JavaScript is executed directly in the browser, making it ideal for adding interactivity to
websites without requiring server communication.
 Event-Driven Programming: JavaScript can respond to user events such as clicks, hover actions, or form
submissions.
 Dynamic Typing: Variables in JavaScript do not have a predefined data type, allowing flexibility in coding.
 Object-Oriented: JavaScript supports objects and methods, making it powerful for building complex applications.
 Platform Independence: It can run on any device or platform that supports a web browser.
 Extensive Libraries and Frameworks: Popular libraries (e.g., React, Angular, Vue.js, jQuery) enhance JavaScript's
functionality and simplify development.

29-11-2024 4
Client-side scripting language
 JavaScript works on the client side by executing directly within a user's web browser. The
browser contains a built-in JavaScript engine (e.g., Google Chrome's V8, Firefox's
SpiderMonkey, or Safari's JavaScriptCore) that interprets and executes JavaScript code
embedded in a web page.

 JavaScript code is usually included in an HTML document using the <script> tag or linked
as an external file using the src attribute. When the browser loads the web page, it parses
the HTML and CSS to construct the Document Object Model (DOM) and then executes the
JavaScript code.
Key Benefits of Client-Side JavaScript:
 Fast Execution: Code runs directly in the browser, reducing server load and improving response
times.
 Interactivity: Enables dynamic content updates, animations, and better user engagement.
 Offline Functionality: Works with offline features like Service Workers.
 Reduced Server Overhead: Many tasks can be performed on the client, decreasing server
dependency.

29-11-2024 5
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box),
 Displaying clocks etc.

JavaScript Example

<script>
document.write("Hello JavaScript by JavaScript");
</script>

29-11-2024 6
JavaScript syntax
JavaScript Values

The JavaScript syntax defines two types of values:


• Fixed values
• Variable values

Fixed values are called Literals.


Variable values are called Variables.

// How to create variables:


var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;

29-11-2024 7
JavaScript Literals & Variables
JavaScript Literals:

1. Numbers are written with or without decimals:

10.50
1001

2. Strings are text, written within double or single quotes:

"John Doe“
'John Doe‘

JavaScript Variables:

• JavaScript uses the keywords var, let and const to declare variables.
let x;
• Variables are containers for storing values.
x = 6;
• An equal sign is used to assign values to variables.
29-11-2024 8
JavaScript Variables
<!DOCTYPE html>
<html>
<body> OUTPUT
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are


JavaScript Variables
undeclared.</p>
<p>They are automatically declared when In this example, x, y, and z are undeclared.
first used.</p>
<script> They are automatically declared when first used.
x = 5;
y = 6;
z = x + y; The value of z is: 11
document.write("The value of z is: " + z);
</script>
</body>
</html>

29-11-2024 9
JavaScript Variables
 The var keyword was used in all JavaScript code from 1995 to 2015.
 The let and const keywords were added to JavaScript in 2015.
 The var keyword should only be used in code written for older browsers.

When to Use var, let, or const?


1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.

29-11-2024 10
JavaScript Functions
 A JavaScript function is a block of code designed to perform a particular task.
 A JavaScript function is executed when "something" invokes it (calls it).
 A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ( ).
 Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
 The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
 The code to be executed, by the function, is placed inside curly brackets: { }

// Function to compute the product of p1 and p2


function myFunction(p1, p2)
{
return p1 * p2;
}
29-11-2024 11
JavaScript Functions
Advantage of JavaScript function
 Functions are useful in organizing the different parts of a script into the several tasks that
must be completed. There are mainly two advantages of JavaScript functions.
 Code reusability: We can call a function several times in a script to perform their tasks so it
saves coding.
 Less coding: It makes our program compact. We don't need to write many lines of code each
time to perform a common task.

Rules for naming functions:


 It must be case sensitive.
 It must be start with alphabetical character (A-Z) or an underscore symbol.
 It cannot contain spaces.
 It cannot be use as a reserve words.

29-11-2024 12
JavaScript Functions
JavaScript Function Arguments

<script>
function getcube(number)
{
alert(number*number*number);
}
</script>
<form>
<input type=button value=click onclick=getcube(4) />
</form>

29-11-2024 13
JavaScript Functions
JavaScript Function Arguments

29-11-2024 14
JavaScript Branches
 Branches allow the program to execute different blocks of code based on conditions.
 Conditional statements are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:

1. Use if to specify a block of code to be executed, if a specified condition is true


2. Use else to specify a block of code to be executed, if the same condition is false
3. Use else if to specify a new condition to test, if the first condition is false
4. Use switch to specify many alternative blocks of code to be executed

29-11-2024 15
JavaScript Branches
if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is
true.
if (condition)
{
// block of code to be executed if the condition is true
}

else Statement
Use the else statement to specify a block of code to be executed if the condition is false.

if (condition)
{
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
29-11-2024 16
JavaScript Branches
else if Statement
Use the else if statement to specify a new condition if the first condition is false.

if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is
false
}

29-11-2024 17
JavaScript Branches
Switch Statement
 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
29-11-2024 18
JavaScript Repetitions (Loops)
Switch Statement
 Repetitions allow executing a block of code multiple times.

JavaScript supports different kinds of loops:


 for - loops through a block of code a number of times
 for/in - loops through the properties of an object
 for/of - loops through the values of an iterable object
 while - loops through a block of code while a specified condition is true
 do/while - also loops through a block of code while a specified condition is true

29-11-2024 19
JavaScript Repetitions (Loops)
For loop
 The for statement creates a loop with 3 optional expressions.
 Expression 1 is executed (one time) before the execution of the code block.
 Expression 2 defines the condition for executing the code block.
 Expression 3 is executed (every time) after the code block has been executed

for (expression 1; expression 2; expression 3)


{
// code block to be executed
}

29-11-2024 20
JavaScript Repetitions (Loops)
For loop Example:
Output:
<!DOCTYPE html>
<html>
<body> JavaScript For Loop
<h2>JavaScript For Loop</h2>
<script>
0
for (let i = 0; i < 5; i++) 1
{ 2
document.write(i + "<br>"); 3
} 4
</script>
</body>
</html>

29-11-2024 21
Task-01
1. Variables
Question :Write a script to store a person's name, age, and favorite color in variables
and display them in the following format:
Output:
Hello, my name is Alice. I am 25 years old, and my favorite color is blue.
2. Functions
Question:
Create a function named addNumbers that takes two numbers as parameters and
returns their sum. Call the function with the numbers 5 and 10 and display the result in
the console.
Expected Output Example:
The sum is: 15

29-11-2024 22
Task-01
3. Branches
Question:
Write a program that checks if a given number (stored in a variable) is even or odd. If
the number is even, display "The number is even", otherwise display "The number is
odd".
Example Input:
let number = 7;
Expected Output Example:
The number is odd

29-11-2024 23
Task-01
4. Repetitions
Question:
Write a for loop that prints the numbers from 1 to 10 in the console, each on a new line.
Expected Output Example:
1 2 3 4 5 6 7 8 9 10
5. Real-World Scenario:
Write a function named greetUser that takes a user's name as a parameter and checks:
If the name is "Admin", display "Welcome, Admin!".
If the name is "Guest", display "Welcome, Guest!".
Otherwise, display "Welcome, [name]!".
Example Input:
greetUser("John");
Expected Output Example:
Welcome, John!
29-11-2024 24
JavaScript Repetitions (Loops)
For...in loop
 The for...in statements combo iterates (loops) over the properties of an object.
 The code block inside the loop is executed once for each property.
for (x in object)
{
code block to be executed
}

29-11-2024 25
JavaScript Repetitions (Loops)
For...in loop Example:

<!DOCTYPE html>
<html>
<body>
<h2> JavaScript "for...in" loop </h2>
<p> Javascript loop displays object data using the loop </p>
<script>
var tutorial = [81, 31, 15, 41, 52, 75, 69, 67];
let i = 1;
for(var tut in tutorial)
{
document.write("values[" +i+ "]: " +tutorial[tut]);
i++;
}
</script>
</body>
</html>
29-11-2024 26
JavaScript Repetitions (Loops)
For...of loop
 The for...of statements combo iterates (loops) over the values of any iterable.
 The code block inside the loop is executed once for each value.
for (x of iterable)
{
code block to be executed
}

29-11-2024 27
JavaScript Repetitions (Loops)
For...of loop Example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Statements</h1>
<h2>The for...of Loop</h2>
<p>Iterate (loop) over the characters of a string:</p>
<script>
let text1 = "JavaScript";
let text2 = " ";
for (let x of text1)
{
text2 += x + " ";
}
document.write(text1 + "<br>" + text2);
</script>
</body>
</html>
29-11-2024 28
JavaScript Repetitions (Loops)
While loop
 The while statement creates a loop (araund a code block) that is executed while a
condition is true.
 The loop runs while the condition is true. Otherwise it stops.

while (condition)
{
code block to be executed
}

29-11-2024 29
JavaScript Repetitions (Loops)
do...while loop
 The do...while statements combo defines a code block to be executed once, and
repeated as long as a condition is true.
 The do...while is used when you want to run a code block at least one time.

do
{
code block to be executed
}
while (condition);

29-11-2024 30
Task-02
Loops:
Question-01:
Password Validation
Write a program that keeps asking the user to enter the correct password ("1234") until
the correct password is entered. (Using do...while)
Question-02:
Menu Selection
Write a program that displays a menu to the user (e.g., 1. Play, 2. Settings, 3. Exit). The
program keeps asking the user to choose an option until they select 3. (Using do...while
& Switch)

29-11-2024 31
JavaScript alert
 The alert() method displays an alert box with a message and an OK button.
 The alert() method is used when you want information to come through to the user.

Syntax:
alert(message)
Example:
alert("Hello\nHow are you?");

29-11-2024 32
JavaScript alert
Example:
<!DOCTYPE html>
<html>
<body>
<h1>The Window Object</h1>
<h2>The alert() Method</h2>
<p>Click the button to see line-breaks in an alert box.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
alert("Hello\nHow are you?");
}
</script>
</body>
</html>

29-11-2024 33
JavaScript prompt
 The prompt() method displays a dialog box that prompts the user for input.
 The prompt() method returns the input value if the user clicks "OK", otherwise it
returns null.

Syntax:
prompt(text, defaultText)
Note:
If the user clicks "OK", the input value is
returned.
Otherwise null is returned.

29-11-2024 34
JavaScript prompt
Example:
<!DOCTYPE html>
<html>
<body>
<h1>The Window Object</h1>
<h2>The prompt() Method</h2>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
let person = prompt("Please enter your name", "Harry Potter");
if (person != null)
{
document.write("Hello " + person + "! How are you today?");
}
}
29-11-2024 </script></body></html> 35
JavaScript confirm
 The confirm() method displays a dialog box with a message, an OK button, and a
Cancel button.
 The confirm() method returns true if the user clicked "OK", otherwise false.

Syntax:
confirm(message)
Note:
true if the user clicked OK, otherwise false.

29-11-2024 36
JavaScript confirm
Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
let text;
if (confirm("Press a button!") == true)
{
text = "You pressed OK!";
} else
{
text = "You canceled!";
}
document.write(text);
}
29-11-2024
</script></body></html> 37
Task-03
Alert, Prompt and confirm methods:
Question:
Imagine you're building a simple web application where the user can provide their name
and decide if they want to proceed with subscribing to a newsletter. Write a JavaScript
program that:
 alert: Greets the user with a welcome message.
 prompt: Asks the user to enter their name.
 confirm: Asks the user for confirmation if they want to subscribe to the
newsletter.
Based on their response:
 If they confirm, display a message saying, "Thank you [Name] for subscribing!"
 If they cancel, display a message saying, "No worries [Name], maybe next time!”

29-11-2024 38
JavaScript Objects
 A JavaScript object is a collection of key-value pairs used to store related data and functionality.
 Objects are a fundamental part of JavaScript and allow you to model real-world entities or concepts
programmatically.
 Objects are variables too. But objects can contain many values.

Example
const car = {type:"Fiat", model:"500", color:"white"};

This code assigns many values (Fiat, 500, white) to


an object named car.

29-11-2024 39
JavaScript Objects
JavaScript Object Literal
An object literal is a list of name:value pairs inside curly braces {}.
Example:
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

Note:
 name:value pairs are also called key:value pairs.
 object literals are also called object initializers.

29-11-2024 40
JavaScript object
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
objectName["propertyName"]
Examples
person.lastName;
person["lastName"];

29-11-2024 41
JavaScript object
Example Object Literal :
<!DOCTYPE html>
<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using an Object Literal</h2>
<script>
// Create an Object:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
document.write(person.firstName + " is " + person.age + " years
old.");
</script></body></html>

29-11-2024 42
JavaScript object
Using the new Keyword
This example create a new JavaScript object using new Object(), and then adds 4 properties:

Example

// Create an Object
const person = new Object();

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

29-11-2024 43
JavaScript Object Methods

29-11-2024 44
JavaScript Object Methods
 Object methods are actions that can be performed on objects.
 A method is a function definition stored as a property value

29-11-2024 45
JavaScript Object Methods
 Object methods are actions that can be performed on objects.
 A method is a function definition stored as a property value

You access an object method with the following syntax:

objectName.methodName()
If you invoke the fullName property with (), it will execute as a function:
Example
name = person.fullName();

29-11-2024 46
JavaScript object method
Example Object method :
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Objects</h1>
<h2>Object Methods</h2>
<p>A method is a function definition stored as a property value.</p>
<script>
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
document.write(person.fullName() + "<br>" + person.id);
</script></body></html>
29-11-2024 47
JavaScript Object Constructors
 In JavaScript, object constructors are used to create multiple objects with similar
properties and methods.
 Object constructors are essentially templates for objects, typically defined using
functions.
Syntax:
function ConstructorName(parameter1, parameter2, ...)
{
this.property1 = parameter1;
this.property2 = parameter2;
// Add methods as needed

this.methodName = function() {
return this.property1 + " " + this.property2;
};

29-11-2024
} 48
JavaScript object Constructor
Example Object Constructor :
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Object Constructors</h1>
<script>
// Constructor Function for Person objects
function Person(first, last, age, eye)
{
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
// Display age
document.write("My father is " + myFather.age + ".");
29-11-2024 </script></body></html> 49
Task-04
Dynamic Object Manipulation
Question:
You are creating a system to manage a library's book collection. Write a JavaScript
program to:
 Create an object for a book with properties title, author, and yearPublished.
 Add a new property available set to true.
 Write a method in the object to mark the book as borrowed by
setting available to false.

29-11-2024 50
DOM (Document Object Model)
 The JavaScript Document Object Model (DOM) is a programming interface for web
documents. It represents the structure of an HTML or XML document as a tree of objects,
allowing developers to manipulate the content, structure, and style of a web page
dynamically.
Key Concepts of the DOM
Tree Structure:
 The DOM represents the document as a tree of nodes.
 Nodes can represent elements, attributes, text, comments, etc.
Hierarchy:
 The document is the root of the DOM tree.
 Child nodes can have their own children, forming a hierarchy.
Objects:
 Each part of the document (HTML elements, attributes, text) is an object that you can
access and manipulate.
29-11-2024 51
DOM (Document Object Model)

Common DOM Methods


Here are some methods used to interact with the DOM:
Selecting Elements
a) document.getElementById(id) - Selects an element by its ID.
b) document.getElementsByClassName(className) - Selects all elements with a specific
class.
c) document.getElementsByTagName(tagName) - Selects all elements with a specific tag.
d) document.querySelector(selector) - Selects the first element that matches a CSS selector.
e) document.querySelectorAll(selector) - Selects all elements that match a CSS selector.

29-11-2024 52
DOM (Document Object Model)

Manipulating Elements
a) element.innerHTML - Sets or gets the HTML content inside an element.
b) element.textContent - Sets or gets the text content of an element.
c) element.style.property - Sets or gets the CSS style properties of an element.
d) element.setAttribute(name, value) - Sets an attribute on an element.
e) element.getAttribute(name) - Gets the value of an attribute.
f) element.classList - Adds, removes, or toggles CSS classes.

29-11-2024 53
DOM (Document Object Model)

Adding/Removing Elements
a) document.createElement(tag) - Creates a new HTML element.
b) parentNode.appendChild(node) - Appends a node as the last child of a parent node.
c) parentNode.insertBefore(newNode, existingNode) - Inserts a node before an existing
child.
d) element.removeChild(child) - Removes a child node from an element.
Event Handling
a) element.addEventListener(event, function) - Attaches an event listener to an element.
b) element.removeEventListener(event, function) - Removes an event listener.

29-11-2024 54
DOM (Document Object Model)
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<button id="changeText">Change Text</button>

<script>
// Select the elements
const title = document.getElementById('title');
const button = document.getElementById('changeText');

// Add an event listener to the button using a function


button.addEventListener('click', function() {
title.textContent = 'Text Changed!';
title.style.color = 'blue'; // Change the text color
});
</script>
</body>
</html>
29-11-2024 55
DOM (Document Object Model)
To access and manipulating web browser elements using DOM, forms, validations, and JavaScript
events in a real-world scenario.
Scenario
A login form with the following features:
1) Validate the input fields to ensure they are not empty.
2) Display a success message when the form is submitted with valid inputs.
3) Highlight fields with errors using red borders.

29-11-2024 56
DOM (Document Object Model)
<!DOCTYPE html> <body>
<html> <h1>Login Form</h1>
<head> <form id="loginForm">
<title>DOM Manipulation with Forms and <label for="username">Username:</label>
Events</title> <input type="text" id="username"
name="username">
<style> <span id="usernameError" class="error-
.error { message"></span>
border: 2px solid red; <br><br>
}
<label for="password">Password:</label>
.success { <input type="password" id="password"
color: green; name="password">
font-weight: bold; <span id="passwordError" class="error-
} message"></span>
.error-message { <br><br>
color: red;
font-size: 12px; <button type="submit"
} id="submitButton">Login</button>
</form>
</style> <p id="output" class="success"></p>
</head>

29-11-2024 57
DOM (Document Object Model)
<script> // Reset errors
// Select form and input elements let isValid = true;
const loginForm = username.classList.remove('error');
document.getElementById('loginForm'); password.classList.remove('error');
usernameError.textContent = '';
const username = passwordError.textContent = '';
document.getElementById('username'); output.textContent = '';
const password = // Validate username
document.getElementById('password'); if (username.value.trim() === '') {
const output = document.getElementById('output'); username.classList.add('error');
usernameError.textContent = 'Username is required';
const usernameError = isValid = false;
document.getElementById('usernameError'); }
const passwordError = // Validate password
document.getElementById('passwordError'); if (password.value.trim() === '') {
password.classList.add('error');
// Add submit event listener passwordError.textContent = 'Password is required';
loginForm.addEventListener('submit', function(event) { isValid = false;
// Prevent the default form submission }
event.preventDefault();
29-11-2024 58
DOM (Document Object Model)
// If valid, display success message
if (isValid) {
output.textContent = 'Login successful!';
username.value = '';
password.value = '';
}
});
</script>
</body>
</html>

29-11-2024 59
Thank You

29-11-2024 60

You might also like