0% found this document useful (0 votes)
30 views98 pages

Client-Side JavaScript Programming Guide

Chapter 4 discusses client-side web programming using JavaScript, explaining its role in adding interactivity to web pages through HTML and CSS. It covers JavaScript syntax, variables, data types, operators, and methods for user input and output. The chapter emphasizes the advantages of using JavaScript, such as reduced server interaction and enhanced user experience.

Uploaded by

milkasecondg
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)
30 views98 pages

Client-Side JavaScript Programming Guide

Chapter 4 discusses client-side web programming using JavaScript, explaining its role in adding interactivity to web pages through HTML and CSS. It covers JavaScript syntax, variables, data types, operators, and methods for user input and output. The chapter emphasizes the advantages of using JavaScript, such as reduced server interaction and enhanced user experience.

Uploaded by

milkasecondg
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

Chapter 4

Client side Web programming


using JavaScript

1
What is Client-side programming?
 Client-side programming refers to the practice of
writing code that executes within a user's web browser.
 When a user visits a website, the web server sends the
HTML, CSS, and JavaScript files to the user's browser.
 The browser then interprets the code and renders the
web page.
 JavaScript allows you to add interactivity to a web
page. Typically,
 We use JavaScript with HTML and CSS to enhance a
web page‘s functionality, such as validating forms,
creating interactive maps, and displaying animated
charts.

2
Client side Programming Using JavaScript
 JavaScript is the scripting language of the Web.
 The script should be included in or referenced by
an HTML document for the code to be interpreted
by the browser.
 It means that a web page need not be a static
HTML, but can include programs that interact with
the user, control the browser, and dynamically
create HTML content.

3
Client side Programming Using JavaScript
What is JavaScript?
 JavaScript was designed to add interactivity to HTML
pages
 JavaScript is a scripting language
 A scripting language is a lightweight programming
language
 JavaScript is usually embedded directly into HTML
pages
 JavaScript is an interpreted language (means that
scripts execute without preliminary compilation)
 JavaScript can be implemented using JavaScript
statements that are placed within the <script>...
</script> HTML tags in a web page.
4
What can a JavaScript Do
 JavaScript can read and write HTML elements
A JavaScript can read and change the content
of an HTML element
 JavaScript can be used to validate data
A JavaScript can be used to validate form data before
it is submitted to a server. This saves the server from
extra processing
 JavaScript can be used to detect the visitor's
browser
A JavaScript can be used to detect the
visitor's browser, and - depending on the browser -
load another page specifically designed for that
browser

5
Advantages of JavaScript
 Less server interaction: You can validate user input
before sending the page off to the server.
This saves server traffic, which means less load on your
server.
 Immediate feedback to the visitors: They don't
have to wait for a page reload to see if they have
forgotten to enter something.
 Increased interactivity: You can create interfaces
that react when the user hovers over them with a
mouse or activates them via the keyboard.
 Richer interfaces: You can use JavaScript to
include such items as drag and drop components
and sliders to give a Rich Interface to your site
visitors.
6
JAVASCRIPT SYNTAX
 JavaScript can be implemented using JavaScript
statements that are placed within the <script>...
</script> HTML tags in a web page.
 You can place the <script> tags, containing your
JavaScript, anywhere within you web page, but it is
normally recommended that you should keep it
within the <head> tags.
 The <script> tag alerts the browser program to start
interpreting all the text between these tags as a
script.

7
JAVASCRIPT SYNTAX
<SCRIPT LANGUAGE=“JavaScript”>
(JavaScript code goes here)
</SCRIPT>
The script tag takes two important attributes:
Language: This attribute specifies what scripting
language you are [Link], its value will be
javascript.
Type: This attribute is what is now recommended to
indicate the scripting language in use and its value
should be set to "text/javascript".
<script language="javascript" type="text/javascript">
JavaScript code
</script>

8
Your First JavaScript
<html>
<body>
<script language="javascript" type="text/javascript">
[Link]("Hello World!")
</script>
</body>
</html>

9
JavaScript Comments
 There are two types of JavaScript comments
 A single line comment written after a double forward
slash (//)
// I am a single line comment
 A multiline comment is written between the strings
(/* */)
/*
I am
a multi line comment
*/

10
Basic JavaScript Input Output
 Accepting user input in JavaScript actually is not a difficult
task.
 JavaScript has a function called prompt, which is used to
accept input from the user. But for the result to be useful for
us, it has to be stored in a variable. Here is a simple example
var name = prompt("Enter your name: ");
alert("Hello " + name);
 Prompt will show a modal windows with a text message, an
input field for the visitor, and the buttons OK/Cancel
 We can also use confirm to get information from a user:- the
function confirm shows a modal window with a question and
two buttons: OK and Cancel
 The result is true if OK is pressed and false otherwise

11
Displaying message in Javascript
 Generating an output in JavaScript can be done in different
[Link] are some common methods:
alert(): This method displays a message in a dialog box that
requires the user to click "OK" to dismiss it. Here's an
example:
alert("Hello, world!");
[Link](): This method outputs a message to the console,
which can be opened in the browser's developer tools.
Here's an example:
[Link]("Hello, world!");
[Link](): This method writes a message directly to
the web page.
[Link]("Hello, world!");

12
Where and how to use JavaScript In HTML
 The HTML <script> tag is used to define a client-side
script (JavaScript).
 JavaScript code is inserted between <script> and
</script> tags.
 The <script> element either contains script
statements, or it points to an external script file
through the src attribute.
 Common uses for JavaScript are image
manipulation, form validation, and dynamic changes
of content

13
JavaScript as a referenced file
3 Ways of Using JavaScript in HTML
1. In header section
2. In Body of html document
3. As external JavaScript file

14
JavaScript in <head>
 In this example, a JavaScript function is placed in
the <head> section of an HTML page.
 The function is invoked (called) when a button is
clicked:

15
Examples
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
[Link] (―hello through header‖);
}
</script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try
it</button>
</body>
</html> 16
JavaScript in <body>...</body>
 In this example, a JavaScript function is placed in
the <body> section of an HTML page.
 The function is invoked (called) when a button is
clicked:

17
Examples
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try
it</button>
<script>
function myFunction() {
[Link](―hello through body‖);
}
</script>
</body>
18
</html>
External JavaScript
 JavaScript can also be placed in external files:
External scripts are practical when the same code is
used in many different web pages.
 JavaScript files have the file extension .js.
 To use an external script, put the name of the
script file in the src (source) attribute of a <script> tag:
 You can place an external script reference in <head>
or <body> as you like.
 The script will behave as if it was located exactly
where the <script> tag is located.
 External scripts cannot contain <script> tags.

19
External JavaScript
External JavaScript Advantages
 Placing scripts in external files has some
advantages:
o It separates HTML and code
o It makes HTML and JavaScript easier to read
and maintain
o Cached JavaScript files can speed up page loads
o To add several script files to one page - use
several script tags

20
Examples
<!DOCTYPE html>
<html>
<body>
<h2>Demo External JavaScript</h2>
<p >A Paragraph.</p>
<button type="button" onclick="myFunction()">Try
it</button>
<p>This example links to "[Link]".</p>
<p>(myFunction is stored in "[Link]")</p>
<script src="[Link]"></script>
</body>
</html>

21
External JavaScript
[Link]
function myFunction()
{
[Link](―hello through external file‖);
}

22
JavaScript –Variables
 Variables are "containers" for storing information.
 JavaScript variables are used to hold values or
expressions.
 A variable can have a short name, like x, or a more
descriptive name, like carname.
 Rules for JavaScript variable names:
 Variable names are case sensitive (y and Y are two
different variables)
 Variable names must begin with a letter or the
underscore character
 Because JavaScript is case-sensitive, variable names
are case-sensitive.
 JavaScript uses the keywords var, let to declare
variable and const to declare constants.
 An equal sign is used to assign values to variables.
23
JavaScript –Variables …
 Declaring (Creating) JavaScript Variables
 Creating variables in JavaScript is most often referred to
as "declaring" variables.
 You can declare JavaScript variables with the var
statement
var x;
var firstname
 After the declaration shown above, the variables are
empty (they have no values yet).
 However, you can also assign values to the variables when
you declare them:
var x=5;
var firstname=―Tola";
 Note: When you assign a text value to a variable, use
quotes around the value.
24
JavaScript Variable Scope
 The scope of a variable is the region of your program in
which it is defined.
 JavaScript variables have only two scopes.
Global Variables: A global variable has global scope
which means it can be defined anywhere in your
JavaScript code.
Local Variables: A local variable will be visible only
within a function where it is defined.
 Function parameters are always local to that function.

25
JavaScript Data types
 Data types basically specify what kind of data can be
stored and manipulated within a program.
 There are six basic data types in JavaScript which can
be divided into three main categories:
Primitive (or primary), composite (or reference), and
special data types.
 String, Number, and Boolean are primitive data types.
 Object, Array, and Function (which are all types of
objects) are composite data types. Whereas
 Undefined and Null are special data types.

26
JavaScript Data types
 Primitive data types can hold only one value at a
time, whereas composite data types can hold
collections of values and more complex entities
The String Data Type
 The string data type is used to represent textual data
(i.e. sequences of characters).
 Strings are created using single or double quotes
surrounding one or more character
var a = 'Hi there!'; // using single quotes
var b = "Hi there!";

27
JavaScript Data types
The Number Data Type
 Represents both integers and decimals
var a = 25; // integer
var b = 80.5; // floating-point number
The Boolean Data Type
 The Boolean data type can hold only two values: true
or false.
 It is typically used to store values like yes
(true) or no (false), on (true) or off (false), etc. as
demonstrate
var isReading = true; // yes, I'm reading
var isSleeping = false; // no, I'm not sleeping

28
JavaScript Data types
The Array Data Type
 An array is a type of object used for storing multiple
values in single variable.
 Each value (also called an element) in an array has a
numeric position, known as its index, and it may
contain data of any data type- numbers, strings,
booleans, functions, objects, and even other arrays.
 The array index starts from 0, so that the first array
element is arr[0] not arr[1]
var colors = ["Red", "Yellow", "Green", "Orange"];

29
JavaScript Data types
The Function Data Type
 JavaScript functions are defined with the function
keyword.
 You can use a function declaration or a function
expression.
function functionName(parameters) {
// code to be executed
}

30
JAVASCRIPT – OPERATORS
What is an operator?
 Operators determine what is done to variables and functions
 Operators "operate" on value
 Let us take a simple expression 4 + 5 is equal to 9. Here
4 and 5 are called operands and ‗+‘ is called
the operator.
Syntax
variable = value operator value
There are different types of JavaScript operators:
o Arithmetic Operators
o Comparison Operators
o Logical (or Relational) Operators
o Assignment Operators
o Conditional (or ternary) Operators
o Special operators

31
JavaScript Arithmetic Operators
 Arithmetic operators are used to perform arithmetic
between variables and/or values.
 Given that y=5, the table below explains the
arithmetic operators:

32
The + Operator Used on Strings
 The + operator can also be used to add string
variables or text values together.
 To add two or more string variables together, use
the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
 After the execution of the statements above, the
variable txt3 contains "What a verynice day".
 To add a space between the two strings, insert a
space into one of the strings or insert a space
into the expression:

33
The + Operator Used on Strings…
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the
variable txt3 contains:
"What a very nice day"

34
JavaScript Assignment Operators
 Assignment operators are used to assign values to
JavaScript variables.
 Given that x=10 and y=5, the table below explains
the assignment operators:

35
Adding Strings and Numbers
 Addition operator (+) works for Numeric as well as
Strings. e.g. "a" + 10 will give "a10―
 If you add a number and a string, the result will be
a string.

36
Comparison Operators
 Comparison operators are used in logical
statements to determine equality or difference
between variables or values.
 Given that x=5, the table below explains the
comparison operators:

37
Comparison Operators…
How Can it be Used
 Comparison operators can be used in conditional
statements to compare values and take action
depending on the result:
if (age<18)
[Link]("Too young");

38
Logical Operators
 Logical operators are used to determine the logic between
variables or values.
 Given that x=6 and y=3, the table below explains the
logical operators:
&& (Logical AND)
 If both the operands are non-zero, then the condition
becomes true.
Ex: (A && B) is true.
|| (Logical OR)
 If any of the two operands are non-zero, then the condition
becomes true.
(A || B) is true.
! (Logical NOT)
 Reverses the logical state of its operand. If a condition is
true, then the Logical NOT operator will make it false.
Ex: ! (A && B) is false.

39
Logical Operators

40
Special operators
typeof operator
o Unary operator
o Indicates the data type of the operand.
Eg
x=123;
alert(typeof(x)); // Number
x="Hello"
alert(typeof(x)); // String

41
Conditional Operator
 JavaScript also contains a conditional operator that
assigns a value to a variable based on some
condition.
? : (Conditional )
 If Condition is true? Then value X : Otherwise value
Y
Syntax
 variablename=(condition)?value1:value2
var a = 10; var b = 20;
 ((a > b) ? 100 : 200) => 200
 ((a < b) ? 100 : 200) => 100

42
Conditional Statements
 While writing a program, there may be a situation
when you need to adopt one out of a given set of paths.
 In such cases, you need to use conditional statements
that allow your program to make correct decisions and
perform right actions.
 In JavaScript we have the following conditional
statements:
 If statement - use this statement if you want to
execute some code only if a specified condition is true

43
Conditional Statements…
 If...else statement - use this statement if you
want to execute some code if the condition is true
and another code if the condition is false
 If...else if....else statement - use this statement if
you want to select one of many blocks of code to be
executed
 Switch statement - use this statement if you want
to select one of many blocks of code to be executed

44
If Statement
 You should use the if statement if you want to
execute some code only if a specified condition is
true.
Syntax
if (expression){
Statement(s) to be executed if expression is true }
 Notice that there is no ..else.. in this syntax. You
just tell the code to execute some code only if the
specified condition is true.

45
If Statement…
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=[Link]();
if (time<10)
{
[Link]("<b>Good morning</b>");
}
</script>

46
If Statement…
<html>
<body>
<script type="text/javascript">
<!–
var age = 20;
if( age > 18 ){
[Link]("<b>Qualifies for driving</b>"); }
//--> </script>
</body>
</html>

47
If...else Statement
 If you want to execute some code if a condition is
true and another code if the condition is not true,
use the if....else statement
Syntax
if (expression){
Statement(s) to be executed if expression is true }
else{
Statement(s) to be executed if expression is false }
 If the resulting value is true, the given statement(s)
in the ‗if‘ block, are executed.
 If the expression is false, then the given
statement(s) in the else block are executed.

48
If...else Statement …
<html>
<body>
<script type="text/javascript">
<!—
var age = 15;
if( age > 18 ){
[Link]("<b>Qualifies for driving</b>");
}
else{
[Link]("<b>Does not qualify for driving</b>");
}
//-->
</script>
</body>
</html>

49
If...else if...else Statement
 You should use the if....else if...else statement if you want to
select one of many sets of lines to execute.
 The if...else if... statement is an advanced form of if…else that
allows JavaScript to make a correct decision out of several
conditions.
if (expression 1){
Statement(s) to be executed if expression 1 is true
}
else if (expression 2){
Statement(s) to be executed if expression 2 is true
}
else if (expression 3){
Statement(s) to be executed if expression 3 is true
}
else{
Statement(s) to be executed if no expression is true }
50
If...else
<html> <body>
if...else Statement…
<script type="text/javascript">
<!–
var book = "maths";
if( book == "history" ){
[Link]("<b>History Book</b>");
}
else if( book == "maths" ){
[Link]("<b>Maths Book</b>");
}
else if( book == "economics" ){
[Link]("<b>Economics Book</b>");
}
else{
[Link]("<b>Unknown Book</b>"); }
//-->
</script> </body> </html>
51
JavaScript - Switch Case
 You should use the switch statement if you want to
select one of many blocks of code to be executed.
 You can use multiple if...else…if statements, as in
the previous chapter, to perform a multiway
branch. However,
 This is not always the best solution, especially
when all of the branches depend on the value of a
single variable.

52
JavaScript - Switch Case
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break; ...
case condition n: statement(s)
break;
default: statement(s) }

53
JavaScript - Switch Case
 The objective of a switch statement is to give an
expression to evaluate and several different
statements to execute based on the value of the
expression.
 The interpreter checks each case against the value
of the expression until a match is found.
 If nothing matches, a default condition will be
used.
 The break statements indicate the end of a
particular case.
 If they were omitted, the interpreter would
continue executing each statement in each of the
following cases
54
JavaScript - Switch Case
<html><body>
<script type="text/javascript">
var grade='A';
[Link]("Entering switch block<br />");
switch (grade) {
case 'A': [Link]("Good job<br />");
break;
case 'B': [Link]("Pretty good<br />");
break;
case 'C': [Link]("Passed<br />");
break;
case 'D': [Link]("Not so good<br />");
break;
case 'F': [Link]("Failed<br />");
break;
default: [Link]("Unknown grade<br />") }
55
</script </body> </html>
JavaScript - While Loops
 The purpose of a while loop is to execute a
statement or code block repeatedly as long as
an expression is true.
 Once the expression becomes false, the loop
terminates.
Syntax
while (expression){
Statement(s) to be executed if expression is true
}

56
JavaScript - While Loops
<html>
<body>
<script type="text/javascript">
var count = 0;
[Link]("Starting Loop ");
while (count < 10){
[Link]("Current Count : " + count + "<br />");
count++;
}
[Link]("Loop stopped!");
</script>
</body>
</html>

57
The do...while Loop
 The do...while loop is similar to the while loop
except that the condition check happens at the end
of the loop.
 This means that the loop will always be executed at
least once, even if the condition is false.
Syntax
do{
Statement(s) to be executed;
}
while (expression);

58
The do...while Loop
<html>
<body>
<script type="text/javascript">
var count = 0;
[Link]("Starting Loop" + "<br >");
do{
[Link]("Current Count : " + count + "<br >");
count++; }
while (count < 5);
[Link] ("Loop stopped!");
</script>
</body>
</html>

59
JavaScript - For Loop
 The 'for' loop is the most compact form of looping.
It includes the following three important parts
 The loop initialization where we initialize our
counter to a starting value.
 The initialization statement is executed before the
loop begins.
 The test statement which will test if a given
condition is true or not.
 If the condition is true, then the code given inside
the loop will be executed, otherwise the control will
come out of the loop.
 The iteration statement where you can increase
or decrease your counter.
 You can put all the three parts in a single line
separated by semicolons.
60
JavaScript - For Loop
Syntax
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}

61
JavaScript - For Loop
<html>
<body>
<script type="text/javascript">
var count;
[Link]("Starting Loop" + "<br>");
for(count = 0; count < 10; count++){
[Link]("Current Count : " + count );
[Link]("<br />");
}
[Link]("Loop stopped!");
</script>
</body>
</html>
62
JavaScript Array
 Arrays are objects in JavaScript which is used to
store a set of values in a single variable name.
 You create an instance of the Array object with the
"new" keyword.
 The length property specifies the number of elements
in an array.
var myArray = new Array(n)
var family_names=new Array(3)
var family_names=newArray(―Mulat",―Shifera",―Siyoum")

63
JavaScript Array
 Data can be of any type, and there can be mixed data
types within the same array if it makes sense for your
data requirements
var ad= [10, ―Ethiopia", ―Asela", ―Dinsho"]
var planet = new Array(9);
planet=newArray(―Mercury‖,‖Venus‖,‖Earth‖,‖Mars‖,―Jupiter‖,―
Saturn‖,‖Uranus‖, ‖Neptune‖,‖Pluto‖); or
var planet= [“Mercury”, ”Venus”, ”Earth”, ”Mars”,
“Jupiter”, “Saturn”, ”Uranus”, ”Neptune”, ”Pluto”];

64
Using Arrays, syntax
 An array is an ordered collection of values referenced
by a single variable name.
 The syntax for creating an array variable is:
var variable = new Array(size);
variable is the name of the array variable
size is the number of elements in the array
(optional)
 To populate the array with values, use:
variable[i]=value;
where i is the ith item of the array.
 The 1st item has an index value of 0.

65
Array ways
 In general, you can create array in three different
ways in JavaScript. The syntax is:
1. arrayName = new Array(arrayLength);
2. arrayName = new Array(element0, element1, ...,
elementN);
3. arrayName = [element0, element1, ..., elementN];
Access an Array
[Link](planet); // Display all elements
[Link](planet[4]); // 4th element of array
for (var i=0; i < [Link]; i++) {
[Link](planet[i] + "<BR>");
}

66
JavaScript Functions
What is Function?
 A function (also known as a method) is a self-contained
piece of code that performs a particular "function".
 You can recognize 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.
 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.

67
JavaScript Functions
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html> 68
JavaScript Functions
 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.

69
JavaScript Functions
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.
 A function with no parameters must include the
parentheses () after the function name:

70
JavaScript Functions
function functionname(){
some code
}
The return Statement
The return statement is used to specify the value that is
returned from the function.
function prod(a,b)
{
x=a*b;
return x;
}
product=prod(2,3);

71
Document Object Model (DOM)
 DOM stands for Document Object Model, which is a
programming interface for web documents.
 A Document object represents the HTML document that is
displayed in that window.
 The way a document content is accessed and modified is called
the Document Object Model, or DOM.
 The Objects are organized in a hierarchy. This hierarchical
structure applies to the organization of objects in a Web
document.
 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.
 The DOM Programming Interface
 The HTML DOM can be accessed with JavaScript (and with
other programming languages).

72
Document Object Model (DOM)
 In the DOM, all HTML elements are defined as
objects.

73
Document Object Model (DOM)
 With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
o JavaScript can change all the HTML elements in
the page
o JavaScript can change all the HTML attributes in
the page
o JavaScript can change all the CSS styles in the
page
o JavaScript can remove existing HTML elements
and attributes
o JavaScript can add new HTML elements and
attributes
o JavaScript can react to all existing HTML events in
the page
o JavaScript can create new HTML events in the page

74
The HTML DOM Document Object
 The document object represents your web page.
 If you want to access any element in an HTML page,
you always start with accessing the document object.
 Finding HTML Elements

75
The HTML DOM Document Object
Changing HTML Elements

76
The HTML DOM Document Object
Changing HTML Content
 The easiest way to modify the content of an HTML
element is by using the innerHTML property.
 To change the content of an HTML element, use this
syntax:
[Link](id).innerHTML = new HTML

77
The HTML DOM Document Object
<html>
<body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p>
<script>
[Link]("p1").innerHTML = "New
text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>

78
The HTML DOM Document Object
Change style:
<html>
<body>
<h1>My First JavaScript</h1>
<p id="demo">JavaScript can change the style of an HTML
element.</p>
<script>
function myFunction() {
[Link]("demo").[Link] = "25px";
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] =
"yellow";
}
</script>
<button type="button" onclick="myFunction()">Click Me!</button>
</body> 79
</html>
Events in JavaScript
 JavaScript events are actions or occurrences that
happen in the browsers ,typically triggered by user
interactions or browsers actions.
 They are fundamental for creating dynamic and
interactive webpage
 Developers can use these events to execute
JavaScript coded responses, which cause buttons to
close windows, messages to be displayed to users,
data to be validated, and virtually any other type of
response imaginable

80
Events in JavaScript
onclick Event Type
 This is the most frequently used event type which occurs
when a user clicks the left button of his mouse.
 You can put your validation, warning etc., against this
event type.
onsubmit Event type
 onsubmit is an event that occurs when you try to submit a
form. You can put your form validation against this event
type
onmouseover and onmouseout
 These two event types will help you create nice effects with
images or even with text as well.
 The onmouseover event triggers when you bring your
mouse over any element and the onmouseout triggers
when you move your mouse out from that element.
81
JavaScript Event Handling
 Events are occur usually as a result of some action
by the user/system.
 With an event handler you can do some action when
an event occurs.

82
JavaScript: Form Validation
 Forms are widely used on the Internet.
 The form input is often sent back to the server or
mailed to a certain e-mail account.
 If the data entered by a client was incorrect or was
simply missing, the server would have to send all
the data back to the client and request that the
form be resubmitted with correct information.
 It is sent only if the input is valid.

83
JavaScript: Form Validation
 form validation may be:
o Form data that typically are checked by a
JavaScript could be:
o has the user left required fields empty?
o has the user entered a valid e-mail address?
o has the user entered a valid date?
o has the user entered text in a numeric field?

84
Example: a script that creates and
validates the above form:

85
Example: a script that creates and
validates the above form:
alert("Email oK!");
<html> if([Link]=="")
<head> alert("No message written");
<script language="JavaScript"> else
function check(form) alert("Message ok");
{ }
if ([Link] == "") </script>
alert("Please enter a string as your </head
name!") <body>
else <h2> <u> Form validation </u> </h2>
alert("Hi " + [Link] + "! Name <form name="first">
ok!"); Enter your name: <input type="text"
if([Link] < 0 || [Link]=="") name="urname"> <br>
alert("Age should be number and greater Enter your age: <input type="text" name="age">
than 0"); <br>
else Enter your e-mail address: <input type="text"
alert("Age ok"); name="email"> <br>
if ([Link] == "" || write message: <textarea name="urmessage"
[Link]('@', 0) == -1) cols=40 rows=10></textarea><br><br>
alert("No valid e-mail address!"); <input type="button" name="validate"
else value="Check Input" onClick="check([Link])">
</body>
</html>

86
Handling Exception in JavaScript
 Exception handling is the process of identifying,
catching, and managing errors in a program to
prevent unexpected crashes.
 It ensures that the application can gracefully
handle errors and continue executing without
breaking functionality.
 JavaScript provides a mechanism to handle errors
using the try –catch-finally block

87
Handling Exception in JavaScript
• try {
statements to try
}
• catch (e) { // Notice: no type
declaration for e
exception-handling statements
}
• finally { // optional, as usual
code that is always executed
}

88
Importance of Exception Handling in JavaScript
 Ensures errors don‘t disrupt the entire program.
 Helps developers track and fix issues efficiently.
 Avoids unexpected failures and provides
meaningful error messages.
Types of Errors in JavaScript
Syntax Errors: Occur when code is incorrectly
written (e.g., missing brackets).
Reference Errors: Accessing variables or functions
that are not defined.
Type Errors: Occurs when operations are performed
on incompatible data types.
Range Errors: Triggered when a number is out of an
allowable range.

89
The try Block
 Executable code that you know may raise exceptions
or cause errors should be placed in a try block.
 When an exception is thrown in the try block, it passes
the error to the catch block, and the necessary actions
can be taken in the catch block.
 If the necessary actions are not taken by
the catch block, the application may behave
abnormally, and a crash is likely to occur.

90
Catch blocks
 The code that should be executed when JavaScript
exceptions happen in the try block is written in
the catch block.
 The exception handling code is usually written in
the catch block.
 Note that the catch block only executes when there
is an error from the try block.
 There can also be more than one catch block to
handle multiple exceptions.

91
Finally blocks
 You can also add a final statement to your
try…catch block and make your code look better.
 With the final block added, the piece of code inside
will get executed regardless of whether the try
block throws an error or not.

92
Example
const a= 10, b = 'string';

try {

[Link](a/b);

[Link](c); //Since the variable is undefined, it will be passed on to catch

catch(error) {

[Link]('An error caught');

[Link]('Error message: ' + error);

finally {
[Link]('This will get executed by default!');

93
JS Cookies
 JavaScript cookie is a small piece of data that a
website saves on your computer or mobile device
when you visit the site.
 It's like a little note the website leaves behind so it
can remember something about you or your visit
when you come back.
 Each time the same computer requests for a page
with a browser, it will send the cookie too. With JS,
you can both create and retrieve cookie values.
 Cookies are a mechanism for storing data in the
remote browser and thus tracking or identifying
return users.
 It is user controled and act as local storage.

94
How It Works?
Cookies are a plain text data record of 5 variable-length
fields:
Expires: The date the cookie will expire. If this is blank,
the cookie will expire when the visitor quits the
browser.
Domain: The domain name of your site.
Path: The path to the directory or web page that set the
cookie. This may be blank if you want to retrieve the
cookie from any directory or page.
Secure: If this field contains the word "secure", then the
cookie may only be retrieved with a secure server. If this
field is blank, no such restriction exists.
Name=Value: Cookies are set and retrieved in the form
of key-value pairs.
95
How It Works? …
 Your server sends some data to the visitor's
browser in the form of a cookie.
 The browser may accept the cookie.
 If it does, it is stored as a plain text record on the
visitor's hard drive.
 Now, when the visitor arrives at another page on
your site, the browser sends the same cookie to the
server for retrieval.
 Once retrieved, your server knows/remembers
what was stored earlier

96
How to Creating, & Storing Cookie
Storing Cookies:
The simplest way to create a cookie is to assign a string
value to the [Link] object, which looks like
this.
[Link] =
"key1=value1;key2=value2;expires=date";

Creating Cookie
The setcookie() function is used to create cookies.
setcookie(name, [value], [expire], [path], [domain],
[secure]);

This sets a cookie named ―Ninja" - that expires at ;, Fri,


26 Nov 2026 [Link] UTC
<script>
setcookie(username=Ninja;expires;Fri, 26 Nov 2026
[Link] UTC");
</script>
97
THANK YOU
98

You might also like