You are on page 1of 87

Chapter 4

Client Side Scripting in JavaScript


1. Introduction to JavaScript

 In the very beginning, web pages were static without any


interaction with the user. They just provide information to the
user as it is.
 Later on, JavaScript is introduced to enable dynamicity (behavior)
in web pages where user has his/her own preferences or control.
 JavaScript is a cross-platform, scripting language modeled.
 Scripting languages are programming languages that are
generally easy to learn, easy to use, excellent for small routines and
applications, and developed to serve a particular purpose.
 Web pages are not the only place where JavaScript is used. Many
desktop and server programs also use JavaScript. Node.JS is best
known.
Cont…

 JavaScript was written for the express purpose of adding


interactivity to Web pages.
 You can embed or integrate commands directly into your HTML
code and the browser will interpret and run them at the
appropriate time.
 Thus, the script should be included in or referenced by an HTML
document for the code to be interpreted by the browser.
 JavaScript is also much more forgiving than compiled languages
such as Java and C++.
 JavaScript is the world’s most popular programming language and its
syntax is simple and easy to read.
Cont…
 JavaScript is an interpreted language rather than compiled (it
doesn’t need pre-compiler).
 Being interpreted does have its advantages. One is platform
independence.
 Because an interpreter performs the translation, you can write
your program once and run it on a variety of platforms.
 Another advantage is that scripting languages are often loosely
typed and more forgiving than compiled languages.
 History of JavaScript (Mocha, Livewire, LiveScript, and currently
JavaScript) and developed by Brendan Eich at Netscape (1995).
What can JavaScript Do?
 JavaScript can change the style of an HTML element.
 Helps in making interactive/dynamic effects in web pages.
 To implement a complex and beautiful things/design on web
pages.
 Provides a good control to the users over the web browser.
 Displaying pop-up windows (alert, confirm and prompt dialog box).
 Dynamic type checking, i.e. JavaScript code is executed when the
user submits the form, and only if all the entries are valid, they
would be submitted to the web server (client side validate or
validate user input before sending the page off to the server).
 Reduces the load on the server as some operation.
 JavaScript is already running in your browser on your computer,
on your tablet, and on your smart-phone.
2. Running the JavaScript

 In HTML, JavaScript programs are executed by the web browser.


 Any time you include JavaScript in an HTML document, you must
enclose it inside a tag.
<script>JavaScript code here...</script>

 These tags alert the browser program to begin interpreting all the
text between these tags as a script.
 Hence, you must specify the precise name of the language in
which the enclosed code is written to JavaScript.
 When the browser receives this signal, it employs its built-in
JavaScript interpreter to handle the code.
Cont…

<script language=”JavaScript”>
//your JavaScript code here
</script>
 Here are some tips to remember when writing
JavaScript commands:
 JavaScript code is case sensitive (e.g. age and Age are
different variables).
 JavaScript accepts both single and double quotes.
 JavaScript statements end with a semi colon (;), also

using semicolon (;) at the end of statement is optional.


Adding JavaScript
 There are three ways to add JavaScript commands to your
Web Pages.
 External file

 Scripts in <body> section

 Scripts in <head> section

I. External File
 If you want to run the same JavaScript on several pages, you can

write a JavaScript in an external file.


 You can place an external script reference in <head> or

<body> as you like.


 Save the external JavaScript file with a .js file extension.
Adding JavaScript…
 The external script cannot contain the <script></script> tags!

 You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an
external text file.

 Placing scripts in external files is used to separate HTML and code, make HTML and
JavaScript easier to read & maintain.
 It is called by the following tag:
<SCRIPT language = "JavaScript" SRC= "filename"> </SCRIPT>
Adding JavaScript…

II. Scripts in <body>


 If you don't want your script to be placed inside a function, or if

your script should write page content, it should be placed in the


body section.
Example:
<html>
<head></head>
<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
Adding JavaScript…

III. Scripts in <head> Scripts to be executed when they are called, or when an event is
triggered, are placed in functions.
 Put your functions in the head section, this way they are all in one place, and they do not

interfere with page content.


JavaScript Display Possibilities

o JavaScript can display data in 4 different ways :

• Writing into an HTML document, using inner HTML


document.getElementById(‘idname').innerHTML="...";
• Writing into the HTML output, using document.write()
• Writing into an alert box, using window.alert()
• Writing into the browser console, using console.log()
Popup Boxes (Message boxes) in JavaScript

 JavaScript has three kind of popup boxes (Built-in global functions): Alert
box, Prompt box, and Confirm box.
alert(“message to display”);
prompt(“message to display”, “default value”);
confirm(“message to display”);
 Anything between double quotes will be displayed as it is in the
web page.
 However, if there is something out of quotes, it is evaluated as
expression and the result will be sent to the web page.
Cont…
 The alert method produces a browser alert box. This box is often used if you want to make sure
information comes through the user.
 alert() displays a modal window that presents a message to the user with a single Ok button to
dismiss the dialog box.
 The prompt is often used if you want the user to input a value before entering a page.
 The prompt display includes a message, field for user input, and two buttons (Ok, and Cancel).
 The prompt(“”) returns string of text entered by user.
 It takes two parameters:
 a message providing the prompt for the response, and
 a default string which is used to fill in the text field.
Example (alert and prompt)
Cont…
 A confirm dialog box presents a message in a modal dialog box along
with Ok and Cancel buttons which is often used if you want the user to
verify or accept something.
 Such dialog boxes can be used to ask the user a question. For example:
you want to take the user’s confirmation before saving, updating or deleting
data.
 The dialog box returns a Boolean value of Ok=true, and Cancel=false;
Comments in JavaScript
 Comments are used to add description to specific code section so as to
describe what the code performs.
 JavaScript supports two types of comments:
 Comments on a single line are preceded by / / .
 Comments that span multiple lines are preceded by / * and
followed by * /

 Example: the following example shows two comments:


//This next line prints text into the document
document.write("This line came from some JavaScript");
/ * This is a multiple-line comment. This line shows an
alert so we know things worked properly * /
alert("The text has been printed");
3. Working with Variables and Data

 Variable: used to hold values. JavaScript statements are composed of values,


Operators, Expressions, Keywords, and Comments.
 Variable starts with Letter, _(Underscore), or $.
 In JavaScript, a value of a variable can be one of several types.
 Table lists JavaScript’s formal data types, with examples of the values.
 Variable names are case sensitive (Y and y are different variables).
Type Example Description
String “John” a series of characters inside quotation marks

Number 4.5 any number not inside quotes

Boolean True a logical true or false


Declaring Variables
All JavaScript variables must be identified with unique names. These unique names are called
identifiers. To declare variable, we use the var keyword, followed by the name of the variable.
Therefore, to declare a new variable called myAge:
var myAge;
 The following are the naming rules of variable:

 Example: Correct variable declaration,


var firstname;
var TH_;
var _firstname;
var $lastname
var myFullName;
 Example: Wrong variable
names:
var first name; //space not allowed
var 89he; //can’t start with digit
Assigning Values to Variables
 After the declaration shown above, the variables are empty which means
they have no data values yet.
 After declaring a variable, it is possible to assign a value to it by using equal
sign (=).
Example

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<script type="text/javascript">
var a=10
var b=23.5
Result=a+b
document.write(Result)
</script>
</body>
</html>
Data types in JavaScript
1. Numeric (integer, double, float)
2. Boolean (true or false): often used in conditional testing
3. String
4. Array, Object, null, Undefined
Data Type Conversions…

 The JavaScript language provides two built-in functions to convert


string representations of numbers to true numbers:
 To use either of these conversion functions, pass the string value
you wish to convert as a parameter to the function.
 parseInt(string)
 parseFloat(string)

 Look at the results of two different string values when passed


through the parseInt() function:
parseInt(“42”) / / result = 42
parseInt(“42.33”) / / result = 42
Data Type Conversions…
 The parseFloat() function returns an integer if it can
 Otherwise, it returns a floating-point number as follows:
parseFloat(“42”); / / result = 42
 parseFloat(“42.33”); / / result = 42.33
Data Type Conversions…
 A more elegant way is to use the toString([radix]) method.
 For example, to convert the dollars variable value to a
string, use this statement:
Var dollars = 2500; dollars.toString() / /
result = “2500”
 You can specify a number base for the string representation of the
number, called the radix, the base number is added as a
parameter to the method name.
 Here is an example of creating a numeric value for
conversion to its hexadecimal equivalent as a string:
var x = 30
var y = x.toString(16) / / result = “1e”
Example:
4. Operators in JavaScript

An Operator: is capable of manipulating a certain value or


operand.
An operator performs some kind of calculation (operation)
or comparison with two values to reach a third value.
Generally, operators can be broadly categorized into four:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators and
4. Logical operators
I. Arithmetic Operators
Arithmetic operators are used to perform arithmetic
operations between variables or values.
Operators and Expressions…

Operator Description

+ Perform addition of numbers

- Perform Subtraction

* Multiply numbers

/ Divide numbers

% Modulus (performs division and gets the remainder)

++ Increment

-- Decrement
Operators and Expressions…

Example:
<script language=“JavaScript”>
var x;
var y=5;
x = y+2; //x=7
x = y-2; //x=3
x = y*2; //x=10
x = y/2; //x=2.5
x = y%2; //x=1
x = ++y; //x=6
x = --y; //x=4
</script>
Operators and Expressions…

II. Assignment Operators


Assignment operators are used to perform assignment operations and
then assign the result to variables.

Operator Description

= Assignment operator
+= Add and then assign

-= Subtract and then assign

*= Multiply and then assign

/= Divide and then assign

%= Modulate and then assign


Operators and Expressions…

<script language=“JavaScript”>
var x=5;
var y=5;
x=y; //x=5;
x+=y; //x=10
x-=y; //x=5
x*=y; //x=25
x/=y; //x=5
</script>
Operators and Expressions…

III. Comparison Operators


Comparison operators help you compare two or more values (operands).
They compare whether the two values are equal or not.

Symbol Description

== Equal to
!= Not equal to
=== Strictly (Exactly) equal to (value and type)
!== Strictly not equal to (not equal value or not equal type)
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Example

Output:
true
true
false
true
false
Operators and Expressions…

IV. Logical (Boolean) Operators


Logical operators are used to determine the logic between variables or
values. It compare boolean expressions and then return true or false.

Operator Description
&& And
|| Or
! Not

Given that x=6 and y=3, the table shows logical operators:
Example Result
(x<10 && y>1) true
(x==5 || y==5) false
!(x==y) true
5. Working with Conditional
Statements
 Conditional statements are used to perform different
actions based on conditions.

 Broadly, there are two ways to execute code


conditionally:
 If statement
 switch statement
Cont…
 If condition
 The simplest program decision is to follow a special branch or

path of the program if a certain condition is true.

 Formal syntax for this construction follows:


if (condition) {
statement[s] if t h e
c o n d i t i o n i s true
}
Cont…

Example:
Cont…
 If . . . else condition
syntax:
if (expression)

{ statement ;}

else

{ statement2;}
Cont…

 if else-if condition..
if (condition) {
statement1
}
else if(condition){
statement2
}
else {
statement3
}


We use if else-if when we have more than two conditions to
check.
Example
Cont…
Switch Statement
 A switch statement allows a program to evaluate an expression and attempt to match the
expression's value to a case label.
 The value of the expression is compared with the value of each case, if a match is
found, the program executes the associated statement.
switch (expression) {

case 1:

statements1

break;

case 2:

statements2

break;
...default:
statements default
}
Looping Statements in JavaScript

• Loops can execute a block of code a number of times. JavaScript


supports different kinds of loops.
1. For Loops
A for loop repeats until a specified condition evaluates to false. A for statement looks
as follows:
for ([initialization]; [condition]; [increment/decrement]){
statement(s)
}
When a for loop executes, the following occurs:
1.The initializing expression initialization, if any, is executed. This expression
usually initializes one or more loop counters.
2.The condition expression is evaluated. If the value of condition is true, the loop
statements execute. If the value of condition is false, the loop terminates.
3.The statement executes.
4.Execute the increment expression, if there is one, and control returns to step 2.
Example:

<html>
<head>
<title> Java Script</title>
</head>
<body>
<script language="JavaScript">
for(var i=0; i<=5; i++)
{
document.write("The value of i is="+i+"<br>");
}
</script>
</body>
</html> Output
The value of i is=0
The value of i is=1
The value of i is=2
The value of i is=3
The value of i is=4
The value of i is=5
Working with Loops…
2. do...while Statement
The do...while statement repeats until a specified condition
evaluates to false.
A do...while statement looks as follows:
do
{
statement //code to be executed
}
while (condition);
Statement executes once before the condition is checked. If
condition is true, the statement executes again. At the end of every
execution, the condition is checked. When the condition is false,
execution stops.
Working with Loops…
Example:
var i=5;
do
{
document.write("tick "+i+"<br>");
i--;
}
while(i>0);
3. while Statement
A while statement executes its statements as long as a specified
condition evaluates to true.
A while statement looks as follows:
while (condition)
{
statement
}
Array in JavaScript
• An array is a special variable, which can store multiple values
in one single variable.
• Arrays are objects.
• Array indexes are zero based which means the first item is zero
(0).i.e. it holds paired index and value.
Why Arrays?
There are several advantages to using JavaScript arrays:
• They are efficient for storing and retrieving data.
• They can be easily manipulated due it has different
methods.
• They have a rich set of methods for working with data.
Cont…
Declaring arrays:
1. Literal method:
-Using square bracket [ ]
2. Constructor method:
-Using array keyword: new Array ( )

Types of Arrays: Reading Assignment


1. Single dimensional
2. Multidimensional
Functions in JavaScript
 Functions are one of the fundamental building blocks in
JavaScript.
 A function is a set of statements (group of code) designed
to perform a specific task/solve a problem.
 To use a function, you must first define it, then your script can call
it.

Defining Functions (Function Declarations)


 A function definition consists the function keyword, followed by:

 The name of the function.

 A list of arguments to the function, separated by commas.

 The statements that define the function, enclosed in curly

braces { }.
Cont…

 The syntax to define function:


function functionName ( [parameter1]...[,parameterN] )
{
statement[s] //body
}
 Function names have the same restrictions as variable names.
 You should devise a name that concisely describes what the function
does.
 It is possible to use multiword names with the intercap format that
start with a verb because functions are action items.
Cont…

The function is invoked (called), when a button is clicked.


Cont…
Function Parameters
 Functionparametersarethenames listedinthefunctiondefinition.
 You can define functions so they receive parameter values from the
calling statement.
 Parameters/arguments provide a mechanism for “handing off” a
value from one statement to another by way of a function call.
 If no parameters occur in the function definition, both the function
definition and call to the function have only empty sets of
parentheses.

 When a function receives parameters, it assigns the incoming values to


the variable names specified in the function definition’s parentheses.
Example

Output: Hailu Abebe


Cont…
 Unlike other variables that you define in your script, function
parameters do not use the var keyword to initialize them.
 They are automatically initialized whenever the function is

called.
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.
Reading Assignment

Local and Global variables in function


Cont…
 The example below returns the product of two numbers (a and b):
<html>
<head>
<script language="JavaScript">
function product(op1, op2)
{
return op1*op2;
}
</script>
</head>
<body>
<script language="JavaScript">
document.write(product(4,3));
</script>
</body>
</html>
JavaScript Events and Objects
1. Managing Events
 Eventsareasignalthatsomethinghasoccurred,orisoccurring.
 Events are occurrences generated by the browser, such as loading a document, or
by the user, such as moving the mouse. They are the user and browser activities to
which we may respond dynamically with a scripting language like JavaScript.
There are several more events that we can capture with JavaScript, but the
ones below are, by far, the most popular.
 Examples of DOM events:
 When a user clicks the mouse
 When a web page has loaded
 When an input field is changed
 When an HTML form is submitted, When a user presses a key and others.
Cont…
Event Event Handler Description
Load onLoad Browser finishes loading a Web document
Unload onUnload Visitor requests a new document in the browser window
Mouseover onMouseOver Visitor moves the mouse over some object in the document window
Mouseout onMouseOut Visitor moves the mouse off of some object in the document window
MouseDown onMouseDown A mouse button was pressed
MouseMove onMouseMove The mouse moved
MouseUp onMouseUp The mouse button was released
Select onSelect Text has been selected.
Click onClick Visitor clicks the mouse button
Focus onFocus Visitor gives focus to or makes active a particular window or form
element by clicking on it or tabbing to it
Blur onBlur A form field lost the focus (user moved to another field)
Change onChange Visitor changes the data selected or contained in a form element
Submit onSubmit Visitor submits a form
Reset onReset Visitor resets a form
Abort onAbort An image failed to load
Change onChange The contents of a field has changed
DblClick onDblClick User double-clicked on this item
Error onError An error occurred while loading an image
Keydown onKeyDown A key was pressed
KeyPress onKeyPress A key was pressed or released
KeyUP onKeyUp A key was released
Events (Mouse and Keyboard)
Events (Form and Touch)
JavaScript Object
• JavaScript Object is used to store collections of data and functionality.
• It is a way of storing related information together.
• JavaScript objects are written with curly braces.
• Object properties are written as name: value pairs separated by
commas.
• There are two ways to create JavaScript objects
• Using the object() constructor
• Using the object literal syntax

Example: Using the object() constructor


Example:(Using the object literal syntax)
Cont…
2. JavaScript Objects
 JavaScript has many built-in objects that you can use to perform
different activities.
 The most important objects are:
• Math
• String
• Date
• History
• Document
• Number
Cont…
2.1 Math Object
 The predefined Math object has properties and methods for
mathematical constants and functions.
 For example, the Math object’s PI property has the value of pi
(3.141...), which you would use in an application as Math.PI;
 Similarly, standard mathematical functions are methods of

Math.
 These include trigonometric, logarithmic, exponential, and other
functions.
 For example: if you want to use the trigonometric function sine,
you would write:
Math.sin(1.56)
 Note that all trigonometric methods of Math take arguments in
radians.
Cont…

Property Value Description

Math.E 2.718281828459045091 Euler’s constant

Math.LN2 0.6931471805599452862 Natural log of 2

Math.LN10 2.302585092994045901 Natural log of 10

Math.LOG2E 1.442695040888963387 Log base-2 of E

Math.LOG10E 0.4342944819032518167 Log base-10 of E

Math.PI 3.141592653589793116 π

Math.SQRT1_2 0.7071067811865475727 Square root of 1/2

Math.SQRT2 1.414213562373095145 Square root of 2


Cont…
Method Syntax Returns
Math.abs(val) Absolute value of val
Math.acos(val) Arc cosine (in radians) of val
Math.asin(val) Arc sine (in radians) of val
Math.atan(val) Arc tangent (in radians) of val
Math.atan2(val1, val2) Angle of polar coordinates x and y
Math.ceil(val) Next integer greater than or equal to val
Math.cos(val) Cosine of val
Math.exp(val) Euler’s constant to the power of val
Math.floor(val) Next integer less than or equal to val
Math.log(val) Natural logarithm (base e) of val
Math.max(val1, val2) The greater of val1 or val2
Math.min(val1, val2) The lesser of val1 or val2
Math.pow(val1, val2) Val1 to the val2 power
Math.random() Random number between 0 and 1
Math.round(val) N+1 when val >= N.5; otherwise N
Math.sin(val) Sine (in radians) of val
Math.sqrt(val) Square root of val
Math.tan(val) Tangent (in radians) of val
Cont…
 Example:
Math.pow(5, 2); //result: 25
Math.sin(90); //result: 1
Math.round(4.7); //result: 5
Math.round(4.4) //result: 4
Cont...
2.2 Date Object
 Most of your date and time work is done with the Date object.

 The basic syntax for generating a new date object is as follows:

 Data objects are static, i.e. you should have refresh it to get

correct date.
var dateObjectName = new Date([parameters])
 The parameter can be:
new Date(“Month dd, yyyy hh:mm:ss”)
new Date(“Month dd, yyyy”)
new Date(yy,mm,dd,hh,mm,ss)
new Date(yy,mm,dd)
new
Date(milliseconds)
Cont…
Method Value Range Description
dateObj.getTime() 0-... returns Milliseconds since 1/1/70 00:00:00 GMT
dateObj.getYear() 70-... returns Specified year minus 1900
returns four-digit year for 2000+
dateObj.getFullYear() 1970-... returns four-digit year (Y2K-compliant)
dateObj.getMonth() 0-11 returns Month within the year (January = 0)
dateObj.getDate() 1-31 returns Date within the month
dateObj.getDay() 0-6 returns Day of week (Sunday = 0)
dateObj.getHours() 0-23 returns Hour of the day in 24-hour time
dateObj.getMinutes() 0-59 returns Minute of the specified hour
dateObj.getSeconds() 0-59 returns Second within the specified minute
dateObj.setTime(val) 0-... sets Milliseconds since 1/1/70 00:00:00 GMT
dateObj.setYear(val) 70-... sets Specified year minus 1900
sets four-digit year for 2000+
dateObj.setMonth(val) 0-11 sets Month within the year (January = 0)
dateObj.setDate(val) 1-31 sets Date within the month
dateObj.setDay(val) 0-6 sets Day of week (Sunday = 0)
dateObj.setHours(val) 0-23 sets Hour of the day in 24-hour time
dateObj.setMinutes(val) 0-59 sets Minute of the specified hour
dateObj.setSeconds(val) 0-59 sets Second within the specified minute
Example:

Output
Sun Nov 12 2023 20:47:21 GMT-0800 (Pacific
Standard Time)
10
2023
Cont…
2.3 String Object
 A string is any text inside a quote pair.

 A quote pair consists of either double quotes or single quotes.

 JavaScript imposes no practical limit on the number of characters


that a string can hold.

 You have two ways to assign a string value to a variable.


1. The simplest is a basic assignment statement:
var myString = “Hello there”;

2. You can also create a string object using the more formal syntax that
involves the new keyword and a constructor function like:
var stringVar = new String(“Hello there”);
Cont…
Method Description
charAt(index) Returns the character at the specified index.
charCodeAt(index) Returns a number indicating the Unicode value of the character at the given index.
concat(string) Combines the text of two strings and returns a new string.
indexOf(string, [start]) Returns the index within the calling String object of the first occurrence of the
specified value, or -1 if not found.
lastIndexOf(string,[start]) Returns the index within the calling String object of the last occurrence of the
specified value, or -1 if not found.
localeCompare(string2) Returns a number indicating whether a reference string comes before or after or is
the same as the given string in sort order.
length Returns the length of the string.
match(regExpression) Used to match a regular expression against a string.
replace(regExpression,replacer) Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
search(regExpression) Executes the search for a match between a regular expression and a specified string.
slice(startIndex [,end]) Extracts a section of a string and returns a new string.
split(delimiter [,limit]) Splits a String object into an array of strings by separating the string into substrings.
substr(start [, length]) Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring(start, end) Returns the characters in a string between the two indexes into a string.
toLowerCase() Returns the calling string value converted to lower case.
toUpperCase() Returns the calling string value converted to uppercase.
toString() Returns a string representing the specified object.
Cont…

Example:
Data Validation in JavaScript
• Data validation is the process of ensuring that the user input is
correct, and useful.
• Typical validation tasks are:
• has the user filled in all required field?
• has a user entered a valid date?
• has the user entered text in numeric field?
• Most often, the purpose data validation is to ensure correct user input.
If an input field contains invalid data, it display a message.
• Validation can be defined by many different methods, and deployed in
many different ways.
• Server-side validation is performed by a web server, after input has
been sent to the server.
• Client-side validation is performed by a web browser, before input is
sent to a web server.
JavaScript Form Validation
• It is important to validate the
form submitted by the user
because it can have
inappropriate values. So,
validation is must to
authenticate user.
• HTML form validation can be
done by JavaScript.
• If a form field (Fname) is empty,
this function alerts a message,
and returns false, to prevent the
form from being submitted.
• Through JavaScript, we can
validate name, password,
email, date, mobile numbers
and more fields.
JavaScript DOM (Document object Model)

The DOM is a W3C (World Wide Web Consortium) standard. It defines a


standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
With the DOM, JavaScript can access and change all the elements of an HTML
documents.
When a web page is loaded, the browser creates a Document Object Model
(window object) of the page.
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic
HTML.
JavaScript can change all the HTML elements and attributes, CSS styles in the
page.
JavaScript can remove existing HTML elements and attributes, add new HTML
elements and attributes, can react to all existing HTML events, can create new
HTML events in the page.
The HTML DOM Tree of Objects
Cont…Example
Cont…
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
What is the HTML DOM?
It defines:
 The HTML elements as objects: In the DOM, all HTML elements are
defined as objects.
 The properties of all HTML elements
 The methods to access all HTML elements
 The events for all HTML elements
In other words: The HTML DOM is a standard for how to get,
change, add, or delete HTML elements.
Cont…
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 programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an
HTML element).
A method is an action you can do (like add or deleting an HTML element).
The following example changes the content (the innerHTML) of
the <p> element with id="demo":
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
In the example above, getElementById is a method, while innerHTML is a property.
The Browser Object Model (BOM)
BOM is a collection of objects that represent the web browser itself.
The window object is supported by all browsers. It represents the browser's
window.
All global JavaScript objects, functions, and variables automatically become
members of the window object.
Simple JavaScript Pop-up Boxes
alert
 Displays an Alert dialog box with a message and an OK button.
 Syntax: alert("message");
 Example: alert(“You’re in a Special Area …”);
alert(“count=“+count);
confirm
 Displays a Confirm dialog box with the specified message and OK and Cancel
buttons.
 Syntax: confirm("message");
 Example: ans = confirm(“Are you sure you want to continue?”);
 If the user clicks on the OK button, the window method confirm will return
true. If the user clicks on the Cancel button, then confirm returns false.
Cont…
eval
 The eval function evaluates a string and returns a value.
 Syntax: eval(stringExpression)
 Example: eval(1+2*3) // gives 7 here
prompt
 The prompt function prompts for a string value.
 Syntax: prompt(“message”) or prompt(“message”, default value)
 This dialog box has two buttons: OK and Cancel. If the user clicks the OK
button, the window method prompt will return the entered value from the text
box. If the user clicks the Cancel button, the window method prompt returns
null.
 Example:
 aString1 = prompt(“Enter Name”);
 aString2 = prompt(“Enter Salary”, 0);
 Note: The return value is a string. Need to convert if a numeric value
is desired. Use parseInt() or parseFloat().
 Example: numSalary = parseInt(aString2);

numSalary = numSalary + 500;


Event handling in JavaScript

 Event Handling is the process of responding to the events.


 JavaScript's interaction with HTML is handled through events that occur when
the user or the browser manipulates a page.
 When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key,
closing a window, resizing a window, etc.
 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 any other type of response imaginable.
 JavaScript events are asynchronous, meaning that they can happen at any time
 e.g., <input type=“button” value=“button1”
onClick=“computeSomething()”>
Event handlers
Cont…
onAbort
 An abort event occurs when a user aborts the loading of an image (for example
by clicking a link or clicking the Stop button)
onBlur
 A blur event occurs when a select, text, or textarea field on a form loses focus.
onChange
 A change event occurs when a select, text, or textarea field loses focus and its
value has been modified.
onClick
 A click event occurs when an object on a form is clicked.

onSelect

 A select event occurs when a user selects some of the text within a text or
textarea field.
Cont…
onError
 An error event occurs when the loading of a document or image causes an error
onFocus
 A focus event occurs when a field receives input focus by tabbing with the
keyboard or clicking with the mouse.
onKeyDown, onKeyPress, onKeyUp
 A keyDown, keyPress, or keyUp event occurs when a user depresses a key,
presses or holds down a key, or releases a key, respectively
onSubmit

 A submit event occurs when a user submits a form


onUnload

 An unload event occurs when you exit a document.


Exception handling in JS

There are three types of errors in programming:


Syntax Errors, Runtime Errors, and Logical Errors.
1. Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JS.
2. Runtime Errors
Runtime errors, also called exceptions, occur during execution time. For example
calling a method that doesn’t exist.
3. Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are
not the result of a syntax or runtime error. Instead, they occur when you make a
mistake in the logic that drives your script and you do not get the result you
expected.
You cannot catch those errors, because it depends on your business requirement
what type of logic you want to put in your program.
The try...catch...finally Statement
The latest versions of JavaScript added exception handling capabilities. JavaScript
implements the try...catch...finally construct as well as the throw operator to handle
exceptions. You can catch programmer-generated and runtime exceptions.
Remember:
• Frameworks/Librarieslike React and Angular are100%based
onJavaScriptandyoucanmasterJavaScriptinordertouse
them!!

Thank you!!

Any Query?

You might also like