SlideShare a Scribd company logo
Unit III – Client-Side Processing and Scripting
Unit III – Client-Side Processing and Scripting
JavaScript Introduction – Variables and Data
Types – Statements – Operators – Literals –
Functions – Objects – Arrays – Built-in Objects
– Regular Expression, Exceptions, Event
handling, Validation – JavaScript
Debuggers.
JavaScript – Introduction
JavaScript can put dynamic text into an HTML page: A JavaScript
statement like this: document.write("<h1>" + name + "</h1>") can write a
variable text into an HTML page
JavaScript can react to events: A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user
clicks on an HTML element
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 will save the
server
from extra processing.
•
•
•
•
JavaScript – Introduction
There are THREE ways that JavaScript can be used within an
HTML file. It can be
1. Put inside <script> tags within the <head> tag (header
scripts),
2. Put inside <script> tags within the <body> tag (body
scripts), or
3. Called directly when certain events occur.
JavaScript – Features
• JavaScript is used in the client side for validating data.
• JavaScript is embedded in HTML.
• JavaScript has no user interfaces. It relies heavily on HTML to provide user
interaction.
• JavaScript is browser dependent.
• JavaScript as a loosely typed language. JavaScript is more flexible. It is
possible to work with variables whose type is not known.
• JavaScript is an Interpreted Language.
JavaScript – Features
• JavaScript is an object-based language. An extension of object-
oriented programming language. Objects in JavaScript encapsulate data &
methods. JavaScript object model is instance based & not inheritance
based.
• JavaScript is event-driven. Code will be in response to events generated by
the user or the system. JavaScript is equipped to handle events.
• HTML objects such as buttons and text boxes are equipped to support
event handlers. Event handlers are functions that are invoked in response to
a message generated by the system or user.
JavaScript – Header Script
<html >
<head>
<title
>Print
ing
Multi
ple
Lines
in a
Dialo
g
Box</
title>
<script type = "text/javascript">
document.write( "Welcome to <br/> JavaScript
</script>
</head>
<body>
</body>
</html>
Programming!" );
document.write – used to display contents on web page.
JavaScript – Body Script
<html>
<head>
<title>Java Script Program – Alert</title>
</head>
<body>
<script type = “text/javascript">
window.alert(" <h1>hello, welcome to javascript! </h1>
");
</script>
</body>
</html>
window.alert – gives the alert message.
JavaScript – Getting Input from User
window.prompt –
to get data
used to prompt the user
<html>
<head><title>Input from
user</title>
<script type="text/javascript">
var fname,lname,name;
fname=window.prompt("Enter the first name");
lname=window.prompt("Enter the last name");
name=fname+lname;
document.write("<h1>My name ist"
+name+"</h1>");
window.alert(name);
</script>
</head>
<body>
<p>refresh the page to restart script</p>
</body></html>
JavaScript – Comments
• Single line comments start with //.
• Multi-line comments start with /* and end with */.
• Adding // in front of a code line changes the code lines from an executable
line to a comment.
JavaScript – Variables
Variables are containers for storing data (storing data
values).
Example:
var x = 5;
var y = 6;
var z = x + y;
JavaScript
String: var s = “india”
– Variables
Number: var n = 0, 100, 3.14159
Boolean: var flag = false or true
Object: var d = new Date();
Function: var Greet = function sayHello() {alert(‘Hello’)}
• JavaScript is a weakly typed language. (i.e.) A simple assignment is
sufficient to change the variable type.
• The typeof keyword can be used to check the current variable type.
JavaScript – Variables
JavaScript Variable Scope
• Global Variables: 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 tothat function.
Example:
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!-- var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local
variable
document.write(myVar); }
//-->
</script>
</body>
</html>
JavaScript – Reserved Words
abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super
JavaScript – Data Types
String: Sequence of characters enclosed in a set of single or double
quotes
•
• Number: Integer or floating point numbers
• Bigint: Used to store integer values that are too big to be represented by a normal
JavaScript Number. Ex: let x = BigInt("123456789012345678901234567890");
• Boolean: Either true/false or a number (0 being false) can be used for Boolean
values
• Undefined: Is a special value assigned to an identifier after it has been declared but
before a value has been assigned to it
• Null: No value assigned which is different from a 0
• Object: Entities that typically represents elements of a HTML page
JavaScript – Data Types
Object Datatypes
Object: JavaScript objects are written with curly braces {}.
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Array: JavaScript arrays are written with square brackets.
const cars = ["Saab", "Volvo", "BMW"];
Date: Used to get year, month and day.
JavaScript – Statements
• JavaScript statements are the commands to tell the
browser to what action to
perform. Statements are separated by semicolon (;).
• JavaScript statement constitutes the JavaScript code which is translated by the
browser line by line.
• Expression statement: Any statement that consists entirely of an
expression
– Expression: code that represents a value
• Block statement: One or more statements enclosed in { }
braces
• Keyword statement: Statement beginning with a keyword, e.g., var or if
• Example: document. getElementById("demo").
JavaScript – Operators
Type Operator Meaning Example
Arithmetic
+ Addition or Unary Plus c = a+b
- Subtraction or Unary Minus d = -a
* Multiplication c = a*b
/ Division c = a/b
% Modulo c = a%b
Relational
< Less than a < 4
> Greater than b > 10
<= Less than equal to b <= 10
>= Greater than equal to a >= 5
== Equal to x == 100
!= Not equal to m != 8
Logical
&& And operator 0 && 1
|| Or operator 0 || 1
Assignment = Is assigned to a = 5
Increment ++ Increment by one ++i or i++
Decrement -- Decrement by one --k or k--
JavaScript
• Literals are simple constants.
– Literals
Example:
34
3.14159
“frog beaks”
‘/nTitle/n’
true
Character Meaning
b backspace
f form feed
n new line
r carriage return
t tab
 backslash character
" double quote
‟ Single quote
ddd Octal number
xdd Tow digit hexadecimal number
xdddd Four digit hexadecimal number
JavaScript – Control Statements
Statement Syntax Example
if-else
if (condition)
statement;
else
statement;
if (a>b)
document.write(“a is greater than b”);
else
document.write(“b is greater than a”);
while
while(condition) {
statements;
}
while(i<5) {
i=i+1;
document.write(“value of I”+i);
}
do…while
do {
Statements;
}
while(conditio
n);
do{
i=i+1;
document.write(“value of I”+i)
}while(i<5);
JavaScript – Control Statements
Statement Syntax Example
for
for(initialization; testcondition;
stepcount) {
Statements;
}
for(i=0; i<5; i++){
document.write(i);
}
Switch…Case
switch(expression) {
case 1:statements
break;
case 2: statements
break;
….
default: statements
}
switch(choice)
{
case 1:c=a+b;
break;
case 2:c=a-b;
break;
}
JavaScript – Control Statements
Statement Syntax Example
break: break;
for(i=10;i>=0;i--) {
if(i==5)
break;
}
Continue: continue;
for(i=10;i>=0;i--) {
if(i==5)
{
X=i;
continue;
}
JavaScript – Control Statements
Statement Syntax Example
break: break;
for(i=10;i>=0;i--) {
if(i==5)
break;
}
Continue: continue;
for(i=10;i>=0;i--) {
if(i==5)
{
X=i;
continue;
}
JavaScript – Functions
• A JavaScript function is a block of code designed to perform a
particular task.
• A function is a group of reusable code which can be called anywhere in
your program.
Syntax
<script type = "text/javascript">
function functionname (parameter-list) {
…..
statements
}
</script>
JavaScript – Functions
Example
JavaScript – Functions
Example – Return Value
JavaScript – Functions
Example – Passing Parameters
JavaScript – Functions
Global Functions
• The top-level function in JavaScript
that
These functions use the built-in objects.
are independent of any specific object.
• encodeURI(uri): Used to encode the URI. This function encodes special characters
except , / ? : @ & = + $ #.
• decodeURI(uri): Decodes the encoded URI.
• parseInt(string,radix): Parse a string and returns the integer value.
• parseFloat(string,radix): Used to obtain the real value from the string.
• eval(string): Used to evaluate the expression.
JavaScript – Functions
Global Functions – Example
JavaScript – Arrays
• Array is a collection of similar type of elements which can be referred by
a common name.
• Any element in an array is referred by an array name followed by index
(i.e., [ ]).
• The particular position of element in an array is called array index or
subscript.
JavaScript – Arrays
• Array Declaration: The array can be created using Array
object.
var ar = new Array(10);
• Array Initialization
var ar = new Array (11,22,33,44,55);
var fruits = new Array( "apple", "orange","mango" );
JavaScript – Arrays
• Array Properties:
Properties Description
constructor Returns a reference to the array function that created the object.
index Represents the zero-based index of the match in the string
input Only present in arrays created by regular expression matches.
length Reflects the number of elements in an array.
prototype Allows you to add properties and methods to an object
JavaScript – Arrays
• Array Methods:
Properties Description
concat() Returns a new array comprised of this array joined with other
array(s) and/or value(s)
every() Returns true if every element in this array satisfies the provided
testing function.
filter() Creates a new array with all of the elements of this array for which
the provided filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf() Returns the first (least) index of an element within the array equal to
the specified value, or -1 if none is found.
join() Joins all elements of an array into a string.
lastIndexOf() Returns the last (greatest) index of an element within the array equal
to the specified value, or -1 if none is found.
JavaScript – Arrays
• Array Methods:
Properties Description
map() Creates a new array with the results of calling a provided function on
every element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new
length of the array.
reduce() Apply a function simultaneously against two values of the array (from
left-to-right) as to reduce it to a single value.
reduceRight() Apply a function simultaneously against two values of the array (from
right-to-left) as to reduce it to a single value.
reverse() Reverses the order of the elements of an array
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
JavaScript – Arrays
• Array Methods:
Properties Description
some() Returns true if at least one element in this array satisfies the provided
testing function
toSource() Represents the source code of an object
sort() Sorts the elements of an array
splice() Adds and/or removes elements from an array
toString() Returns a string representing the array and its element
Unshift() Adds one or more elements to the front of an array and returns the
new length of the array
JavaScript – Arrays
Write a JavaScript to print the largest and smallest values
among 10 elements of an
array.
JavaScript – Arrays
Write a JavaScript to print the largest and smallest values
among 10 elements of an
array.
JavaScript – Document Object Modeling
• Defining the standard for accessing and manipulating HTML, XML
and other scripting languages.
• DOM is a set of platform independent and language neutral Application
Programming Interface (API) which describes how to
and
access and
manipulate the
documents.
information stored in XML, HTML JavaScript
JavaScript – Document Object Modeling
DOM Methods
Method Description
getElementById Used to obtain the specific element which specified by some id
within the script
createElement Used to create an element node
createTextNode Used for creating text node
createAttribute Used for creating attribute
appendChild For adding a new child to specified node
removeChild For removing a new child to specified node
getAttribute To return a specified attribute value
setAttribute To set or change the specified attribute to the specified value
JavaScript – Document Object Modeling
DOM Properties
Property Description
attributes Used to get the attribute nodes of the node
parentNode To obtain the parent node of the specific node
childNodes To obtain the child nodes of the specific parent node
innerHTML To get the text value of a node
JavaScript – Document Object Modeling
DOM Example
JavaScript – Objects
• The web designer can create an object and can set its properties as per
their requirements.
• The object can be created using new expression.
• Syntax:
Myobj = new Object();
JavaScript – Build-in Objects
Math Object
• The math object provides
constants and functions.
properties and methods for mathematical
• Math is not a constructor.
• All the properties and methods of Math are static and can be called
by using Math as an object without creating it.
• Example
document.write(math.min(3,4,5));
document.write(math.sin(30));
JavaScript – Build-in Objects
Math Methods
Methods Description
abs(num) Returns the absolute value of a number
sin(num), cos(num),
tan(num) Returns the sine, cosine, tangent() of a number
min(a,b), max(a,b) Returns the smallest / largest of zero or more numbers
round(num) Returns the value of a number rounded to the nearest integer
random() Returns a pseudo-random number between 0 and 1
exp(num) Returns EN, where N is the argument, and E is Euler's
constant, the base of the natural logarithm
ceil(num), floor(num) Returns the largest integer less than or equal to a number
pow(a,b) Returns base to the exponent power, that is, base exponent
sqrt(num) Returns the square root of a number
log(num) Returns the natural logarithm (base E) of a number
JavaScript – Build-in Objects
Number Object
• Represents numerical data, either integers or floating-point
numbers.
• Syntax:
var val = new Number(number);
• Properties
Methods Description
MAX_VALUE Display largest possible number
MIN_VAUE Display smallest possible number
NaN Display NaN, When not a number
PI Display the value PI
POSITIVE_INFINITY Display the positive infinity
NAGATIVE_INFINITY Display the negative infinity
JavaScript – Build-in Objects
Date Object
• Used to obtain the date and time.
• Date objects are created with the new
Date( ).
• Syntax:
var my_date = new Date( )
JavaScript – Build-in Objects
Date Object
Methods Description
getTime() Return the number of milliseconds. [1970 to current year]
getDate() Return the current date based on computers local time
getUTCDate() Return the current date obtained from UTC
getDay() Return the current day. [0 – 6 => Sunday – Saturday]
getUTCDay() Return the current day based on UTC. [0 – 6 => Sunday – Saturday]
getHours() Returns the hour value ranging from 0 to 23, based on local time
getUTCHours() Returns the hour value ranging from 0 to 23, based on UTC time zone
getMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on local time
getUTCMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on UTC
getMinutes() Returns the minute value ranging from 0 to 59, based on local time
getUTCMinutes() Returns the minute value ranging from 0 to 59, based on UTC time zone
getSeconds() Returns the second value ranging from 0 to 59, based on local time
getUTCSeconds() Returns the second value ranging from 0 to 59, based on UTC time zone
setDate(value) To set the desired date using local or UTC timing zone
setHour(hr,
minute,second,ms) To set the desired time using local or UTC timing zone
JavaScript – Build-in Objects
String Object
• A collection of characters
• It wraps Javascript's string primitive data type with a number of helper methods.
• Syntax:
var val = new String(string);
JavaScript – Build-in Objects
String Object
Methods Description
concat(str) Concatenates the two strings
charAt(index_val) Return the character specified by value index_val
substring(begin, end) Returns the substring specified by begin and end character
toLowerCase() Used to convert all uppercase letters to lowercase
toUpperCase() Used to convert all lowercase letters to uppercase
valueOf() Returns the value of the string
JavaScript – Build-in Objects
Boolean Object
• Represents two values, either "true" or "false".
• If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the
empty string (""), the object has an initial value of false.
the object
Methods Description
toSource() Returns a string containing the source of the Boolean object
toString()
Returns a string of either "true" or "false" depending upon the value of
valueOf() Returns the primitive value of the Boolean object
JavaScript
Object
– Build-in Objects
Window
_parent – URL is loaded in parent window
Methods Description
alert(String) Displays the alert box with some message and OK button
confirm(String) Displays the alert box with some message and OK button and Cancel button
prompt(String) Displays a dialog box which allows the user to input some data
open(URL, width,
height)
Opens a new window with specified URL
_blank – URL is loaded in new window
_self – URL replaces currently opened window
_top – URL replaces the currently opened frameset
close() Close the current window
moveBy() Move the window from the current position to some other position
moveTo() Moves the window to specific position
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window by the specified width and height
JavaScript – Regular Expression
• A regular expression is a special text string that defines the search
pattern.
• It is a logical expression.
• Create a regular expression pattern using forward slash /.
• It is a powerful pattern-matching and search-and-replace functions on
text.
• Syntax:
var pat = /pattern/
JavaScript – Regular Expression
Special Characters Description
. Any character expect new line
? 0 or 1
* 0 or more occurrence
+ 1 or more occurrence
^ Start of the String
$ End of the String
[abc] Any of the characters a, b, or c
[A-Z] Any character from uppercase A to uppercase Z
JavaScript – Regular Expression
Methods Description
exec Tests for a match in a string. If it finds a match, it returns a
result
array, otherwise it returns null.
test Tests for a match in a string. If it finds a match, it returns
true,
otherwise it returns false.
match Tests for a match in a string. It returns an array of information or null
on a mismatch.
search Tests for a match in a string. It returns the index of the match, or -1
if
the search fails.
replace Tests for a match in a string and replaces the matched substring with
a replacement substring.
split Uses the regular expression or a fixed string to break a string into an
array of substring.
JavaScript – Regular Expression
JavaScript – Regular Expression
JavaScript – Regular Expression
JavaScript – Regular Expression
X +
0 Phone Number Checking X 0 Phone Number Checking v
0. c!:J '{:( a
K :
� � C CD File fVolumes/Kav1ya/Academ1cs/lT2253%20-%20WE/Examples/JavaScript%20Examples/phoneno.html
0 Sci-Hub I The ma e Tamil Jothida Pala ,j Microsoft Teams 0 � AIRCC Publishing � Machine Learning
Enter Phone Number: I (333)
5555555
Country Code:
1�3_3
�
Phone Number: �5 5_5 �
Click
JavaScript – Exceptions
• Exception handling is a mechanism that handles the
runtime errors so that
the normal flow of the application can be maintained.
Statements:
• try: Test a block of code for errors
• catch: Handle the error
• throw: Create custom errors
• finally: Execute code, after try and catch, regardless of the result.
JavaScript – Exceptions
Syntax
try {
//Block of code to try
}
catch(err) {
//Block of code to handle errors
}
JavaScript – Exceptions
JavaScript – Exceptions
JavaScript – Exceptions
JavaScript – Event Handling
• Event: An activity that represents a change
mouse clicks, key press.
in the environment. Example:
• Event Handler: A script that gets executed in response to these events. It
enables the web document to respond that user activities through the
browser window.
• Event Registration: The process of connecting even handler to an event. It
can be done using two methods:
– Assigning the tag attributes
– Assigning the handler address to object properties
JavaScript – Event Handling
Event Description Associated Tags
onclick The user clicks an HTML element <a>, <input>
ondbclick The user double clicks an HTML element <a>, <input>,
<button>
onmouseup The user releases the left mouse button Form elements
onmousedown The user clicks the left mouse button Form elements
onmousemove The user moves the mouse Form elements
onmouseover The user moves the mouse over an HTML element Form elements
onmouseout The user moves the mouse away from an HTML
element
Form elements
onkeydown The user pushes a keyboard key Form elements
onkeyup The user releases a key from keyboard Form elements
onkeypress The user presses the key button Form elements
JavaScript – Event Handling
Event Description Associated Tags
onchange An HTML element has been changed <input>
<textarea>
<select>
onsubmit The user clicks the submit button <form>
onreset The user clicks the reset button <form>
onselect On selection <input>, <textarea>
onload After getting the document is loaded <body>
onunload The user exits the document <body>
JavaScript – Event Handling
Syntax:
<input type = "button" name = “My_button” onclick = ”display()” />
Tag attribute
Event handler
JavaScript – Event Handling
onclick Event Handling:
JavaScript – Event Handling
onclick Event Handling:
JavaScript – Event Handling
onload Event Handling:
JavaScript – Event Handling
onload Event Handling:
JavaScript – Event Handling
mouseover and mouseout Event Handling:
JavaScript – Event Handling
mouseover and mouseout Event Handling:
JavaScript – Event Handling
keypress Event Handling:
JavaScript – Event Handling
keypress Event Handling:
JavaScript – Validation
• Various control objects are placed on the form.
• These control objects are called widgets.
• These widgets used in JavaScript are Textbox, Radio button, Check
box
and so on.
• In JavaScript, the validation of these widgets is an important task.
JavaScript – Validation
Create the following HTML form and do the following validation in Java
Script.
a) Check fields for not Empty
b)
c)
Email ID validation.
Numbers and special characters not allowed in First name and Last
name.
JavaScript – Debuggers
• The standard traditional method of debugging the
JavaScript is using
alert() to display the values of the corresponding variables.
• Use API methods for debugging the JavaScript.
• Use log() function console API.
JavaScript – Debuggers
• The standard traditional method of debugging the
JavaScript is using
alert() to display the values of the corresponding variables.
• Use API methods for debugging the JavaScript.
• Use log() function console API.
JavaScript – Debuggers
JavaScript – Debuggers
JavaScript – Examples
1. Design the simple calculator in JavaScript with the following operations:
Addition, Subtraction, Multiplication and Division.
Use JavaScript and HTML to create a page with two panes. The first pane (on
the
2.
left) should have a text area where HTML code can be typed by the user. The
pane on the right side should display the preview of the HTML code
user, as it would be seen in the browser.
Write a JavaScript to get the current hours as h and do the following:
If h>=0 and h<12 then print “Good Morning”
typed by the
3.
If h>=12 and h<4 then print “Good Noon”
If h>=4 and h<8 then print “Good Evening”
Otherwise print “Good night”
Ad

More Related Content

Similar to Unit III.pptx IT3401 web essentials presentatio (20)

JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
Soumen Santra
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
AlkanthiSomesh
 
Html JavaScript and CSS
Html JavaScript and CSSHtml JavaScript and CSS
Html JavaScript and CSS
Radhe Krishna Rajan
 
Java script
Java scriptJava script
Java script
Abhishek Kesharwani
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
rashmiisrani1
 
Java script
Java scriptJava script
Java script
Rajkiran Mummadi
 
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
kavigamage62
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
Java scipt
Java sciptJava scipt
Java scipt
Ashish Gajjar Samvad Cell
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
ambuj pathak
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
SANTOSH RATH
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
Java script
Java scriptJava script
Java script
Ravinder Kamboj
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
Jyothishmathi Institute of Technology and Science Karimnagar
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
MattMarino13
 
CHAPTER 3 JS (1).pptx
CHAPTER 3  JS (1).pptxCHAPTER 3  JS (1).pptx
CHAPTER 3 JS (1).pptx
achutachut
 
HNDIT1022 Week 08, 09 10 Theory web .pptx
HNDIT1022 Week 08, 09  10 Theory web .pptxHNDIT1022 Week 08, 09  10 Theory web .pptx
HNDIT1022 Week 08, 09 10 Theory web .pptx
IsuriUmayangana
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
MattMarino13
 

Recently uploaded (20)

Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Ad

Unit III.pptx IT3401 web essentials presentatio

  • 1. Unit III – Client-Side Processing and Scripting
  • 2. Unit III – Client-Side Processing and Scripting JavaScript Introduction – Variables and Data Types – Statements – Operators – Literals – Functions – Objects – Arrays – Built-in Objects – Regular Expression, Exceptions, Event handling, Validation – JavaScript Debuggers.
  • 3. JavaScript – Introduction JavaScript can put dynamic text into an HTML page: A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events: A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element 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 will save the server from extra processing. • • • •
  • 4. JavaScript – Introduction There are THREE ways that JavaScript can be used within an HTML file. It can be 1. Put inside <script> tags within the <head> tag (header scripts), 2. Put inside <script> tags within the <body> tag (body scripts), or 3. Called directly when certain events occur.
  • 5. JavaScript – Features • JavaScript is used in the client side for validating data. • JavaScript is embedded in HTML. • JavaScript has no user interfaces. It relies heavily on HTML to provide user interaction. • JavaScript is browser dependent. • JavaScript as a loosely typed language. JavaScript is more flexible. It is possible to work with variables whose type is not known. • JavaScript is an Interpreted Language.
  • 6. JavaScript – Features • JavaScript is an object-based language. An extension of object- oriented programming language. Objects in JavaScript encapsulate data & methods. JavaScript object model is instance based & not inheritance based. • JavaScript is event-driven. Code will be in response to events generated by the user or the system. JavaScript is equipped to handle events. • HTML objects such as buttons and text boxes are equipped to support event handlers. Event handlers are functions that are invoked in response to a message generated by the system or user.
  • 7. JavaScript – Header Script <html > <head> <title >Print ing Multi ple Lines in a Dialo g Box</ title> <script type = "text/javascript"> document.write( "Welcome to <br/> JavaScript </script> </head> <body> </body> </html> Programming!" ); document.write – used to display contents on web page.
  • 8. JavaScript – Body Script <html> <head> <title>Java Script Program – Alert</title> </head> <body> <script type = “text/javascript"> window.alert(" <h1>hello, welcome to javascript! </h1> "); </script> </body> </html> window.alert – gives the alert message.
  • 9. JavaScript – Getting Input from User window.prompt – to get data used to prompt the user <html> <head><title>Input from user</title> <script type="text/javascript"> var fname,lname,name; fname=window.prompt("Enter the first name"); lname=window.prompt("Enter the last name"); name=fname+lname; document.write("<h1>My name ist" +name+"</h1>"); window.alert(name); </script> </head> <body> <p>refresh the page to restart script</p> </body></html>
  • 10. JavaScript – Comments • Single line comments start with //. • Multi-line comments start with /* and end with */. • Adding // in front of a code line changes the code lines from an executable line to a comment.
  • 11. JavaScript – Variables Variables are containers for storing data (storing data values). Example: var x = 5; var y = 6; var z = x + y;
  • 12. JavaScript String: var s = “india” – Variables Number: var n = 0, 100, 3.14159 Boolean: var flag = false or true Object: var d = new Date(); Function: var Greet = function sayHello() {alert(‘Hello’)} • JavaScript is a weakly typed language. (i.e.) A simple assignment is sufficient to change the variable type. • The typeof keyword can be used to check the current variable type.
  • 13. JavaScript – Variables JavaScript Variable Scope • Global Variables: 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 tothat function. Example: <html> <body onload = checkscope();> <script type = "text/javascript"> <!-- var myVar = "global"; // Declare a global variable function checkscope( ) { var myVar = "local"; // Declare a local variable document.write(myVar); } //--> </script> </body> </html>
  • 14. JavaScript – Reserved Words abstract else instanceof switch boolean enum int synchronized break export interface this byte extends long throw case false native throws catch final new transient char finally null true class float package try const for private typeof continue function protected var debugger goto public void default if return volatile delete implements short while do import static with double in super
  • 15. JavaScript – Data Types String: Sequence of characters enclosed in a set of single or double quotes • • Number: Integer or floating point numbers • Bigint: Used to store integer values that are too big to be represented by a normal JavaScript Number. Ex: let x = BigInt("123456789012345678901234567890"); • Boolean: Either true/false or a number (0 being false) can be used for Boolean values • Undefined: Is a special value assigned to an identifier after it has been declared but before a value has been assigned to it • Null: No value assigned which is different from a 0 • Object: Entities that typically represents elements of a HTML page
  • 16. JavaScript – Data Types Object Datatypes Object: JavaScript objects are written with curly braces {}. const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; Array: JavaScript arrays are written with square brackets. const cars = ["Saab", "Volvo", "BMW"]; Date: Used to get year, month and day.
  • 17. JavaScript – Statements • JavaScript statements are the commands to tell the browser to what action to perform. Statements are separated by semicolon (;). • JavaScript statement constitutes the JavaScript code which is translated by the browser line by line. • Expression statement: Any statement that consists entirely of an expression – Expression: code that represents a value • Block statement: One or more statements enclosed in { } braces • Keyword statement: Statement beginning with a keyword, e.g., var or if • Example: document. getElementById("demo").
  • 18. JavaScript – Operators Type Operator Meaning Example Arithmetic + Addition or Unary Plus c = a+b - Subtraction or Unary Minus d = -a * Multiplication c = a*b / Division c = a/b % Modulo c = a%b Relational < Less than a < 4 > Greater than b > 10 <= Less than equal to b <= 10 >= Greater than equal to a >= 5 == Equal to x == 100 != Not equal to m != 8 Logical && And operator 0 && 1 || Or operator 0 || 1 Assignment = Is assigned to a = 5 Increment ++ Increment by one ++i or i++ Decrement -- Decrement by one --k or k--
  • 19. JavaScript • Literals are simple constants. – Literals Example: 34 3.14159 “frog beaks” ‘/nTitle/n’ true Character Meaning b backspace f form feed n new line r carriage return t tab backslash character " double quote ‟ Single quote ddd Octal number xdd Tow digit hexadecimal number xdddd Four digit hexadecimal number
  • 20. JavaScript – Control Statements Statement Syntax Example if-else if (condition) statement; else statement; if (a>b) document.write(“a is greater than b”); else document.write(“b is greater than a”); while while(condition) { statements; } while(i<5) { i=i+1; document.write(“value of I”+i); } do…while do { Statements; } while(conditio n); do{ i=i+1; document.write(“value of I”+i) }while(i<5);
  • 21. JavaScript – Control Statements Statement Syntax Example for for(initialization; testcondition; stepcount) { Statements; } for(i=0; i<5; i++){ document.write(i); } Switch…Case switch(expression) { case 1:statements break; case 2: statements break; …. default: statements } switch(choice) { case 1:c=a+b; break; case 2:c=a-b; break; }
  • 22. JavaScript – Control Statements Statement Syntax Example break: break; for(i=10;i>=0;i--) { if(i==5) break; } Continue: continue; for(i=10;i>=0;i--) { if(i==5) { X=i; continue; }
  • 23. JavaScript – Control Statements Statement Syntax Example break: break; for(i=10;i>=0;i--) { if(i==5) break; } Continue: continue; for(i=10;i>=0;i--) { if(i==5) { X=i; continue; }
  • 24. JavaScript – Functions • A JavaScript function is a block of code designed to perform a particular task. • A function is a group of reusable code which can be called anywhere in your program. Syntax <script type = "text/javascript"> function functionname (parameter-list) { ….. statements } </script>
  • 27. JavaScript – Functions Example – Passing Parameters
  • 28. JavaScript – Functions Global Functions • The top-level function in JavaScript that These functions use the built-in objects. are independent of any specific object. • encodeURI(uri): Used to encode the URI. This function encodes special characters except , / ? : @ & = + $ #. • decodeURI(uri): Decodes the encoded URI. • parseInt(string,radix): Parse a string and returns the integer value. • parseFloat(string,radix): Used to obtain the real value from the string. • eval(string): Used to evaluate the expression.
  • 29. JavaScript – Functions Global Functions – Example
  • 30. JavaScript – Arrays • Array is a collection of similar type of elements which can be referred by a common name. • Any element in an array is referred by an array name followed by index (i.e., [ ]). • The particular position of element in an array is called array index or subscript.
  • 31. JavaScript – Arrays • Array Declaration: The array can be created using Array object. var ar = new Array(10); • Array Initialization var ar = new Array (11,22,33,44,55); var fruits = new Array( "apple", "orange","mango" );
  • 32. JavaScript – Arrays • Array Properties: Properties Description constructor Returns a reference to the array function that created the object. index Represents the zero-based index of the match in the string input Only present in arrays created by regular expression matches. length Reflects the number of elements in an array. prototype Allows you to add properties and methods to an object
  • 33. JavaScript – Arrays • Array Methods: Properties Description concat() Returns a new array comprised of this array joined with other array(s) and/or value(s) every() Returns true if every element in this array satisfies the provided testing function. filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. forEach() Calls a function for each element in the array. indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. join() Joins all elements of an array into a string. lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
  • 34. JavaScript – Arrays • Array Methods: Properties Description map() Creates a new array with the results of calling a provided function on every element in this array. pop() Removes the last element from an array and returns that element. push() Adds one or more elements to the end of an array and returns the new length of the array. reduce() Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. reduceRight() Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value. reverse() Reverses the order of the elements of an array shift() Removes the first element from an array and returns that element. slice() Extracts a section of an array and returns a new array.
  • 35. JavaScript – Arrays • Array Methods: Properties Description some() Returns true if at least one element in this array satisfies the provided testing function toSource() Represents the source code of an object sort() Sorts the elements of an array splice() Adds and/or removes elements from an array toString() Returns a string representing the array and its element Unshift() Adds one or more elements to the front of an array and returns the new length of the array
  • 36. JavaScript – Arrays Write a JavaScript to print the largest and smallest values among 10 elements of an array.
  • 37. JavaScript – Arrays Write a JavaScript to print the largest and smallest values among 10 elements of an array.
  • 38. JavaScript – Document Object Modeling • Defining the standard for accessing and manipulating HTML, XML and other scripting languages. • DOM is a set of platform independent and language neutral Application Programming Interface (API) which describes how to and access and manipulate the documents. information stored in XML, HTML JavaScript
  • 39. JavaScript – Document Object Modeling DOM Methods Method Description getElementById Used to obtain the specific element which specified by some id within the script createElement Used to create an element node createTextNode Used for creating text node createAttribute Used for creating attribute appendChild For adding a new child to specified node removeChild For removing a new child to specified node getAttribute To return a specified attribute value setAttribute To set or change the specified attribute to the specified value
  • 40. JavaScript – Document Object Modeling DOM Properties Property Description attributes Used to get the attribute nodes of the node parentNode To obtain the parent node of the specific node childNodes To obtain the child nodes of the specific parent node innerHTML To get the text value of a node
  • 41. JavaScript – Document Object Modeling DOM Example
  • 42. JavaScript – Objects • The web designer can create an object and can set its properties as per their requirements. • The object can be created using new expression. • Syntax: Myobj = new Object();
  • 43. JavaScript – Build-in Objects Math Object • The math object provides constants and functions. properties and methods for mathematical • Math is not a constructor. • All the properties and methods of Math are static and can be called by using Math as an object without creating it. • Example document.write(math.min(3,4,5)); document.write(math.sin(30));
  • 44. JavaScript – Build-in Objects Math Methods Methods Description abs(num) Returns the absolute value of a number sin(num), cos(num), tan(num) Returns the sine, cosine, tangent() of a number min(a,b), max(a,b) Returns the smallest / largest of zero or more numbers round(num) Returns the value of a number rounded to the nearest integer random() Returns a pseudo-random number between 0 and 1 exp(num) Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm ceil(num), floor(num) Returns the largest integer less than or equal to a number pow(a,b) Returns base to the exponent power, that is, base exponent sqrt(num) Returns the square root of a number log(num) Returns the natural logarithm (base E) of a number
  • 45. JavaScript – Build-in Objects Number Object • Represents numerical data, either integers or floating-point numbers. • Syntax: var val = new Number(number); • Properties Methods Description MAX_VALUE Display largest possible number MIN_VAUE Display smallest possible number NaN Display NaN, When not a number PI Display the value PI POSITIVE_INFINITY Display the positive infinity NAGATIVE_INFINITY Display the negative infinity
  • 46. JavaScript – Build-in Objects Date Object • Used to obtain the date and time. • Date objects are created with the new Date( ). • Syntax: var my_date = new Date( )
  • 47. JavaScript – Build-in Objects Date Object Methods Description getTime() Return the number of milliseconds. [1970 to current year] getDate() Return the current date based on computers local time getUTCDate() Return the current date obtained from UTC getDay() Return the current day. [0 – 6 => Sunday – Saturday] getUTCDay() Return the current day based on UTC. [0 – 6 => Sunday – Saturday] getHours() Returns the hour value ranging from 0 to 23, based on local time getUTCHours() Returns the hour value ranging from 0 to 23, based on UTC time zone getMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on local time getUTCMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on UTC getMinutes() Returns the minute value ranging from 0 to 59, based on local time getUTCMinutes() Returns the minute value ranging from 0 to 59, based on UTC time zone getSeconds() Returns the second value ranging from 0 to 59, based on local time getUTCSeconds() Returns the second value ranging from 0 to 59, based on UTC time zone setDate(value) To set the desired date using local or UTC timing zone setHour(hr, minute,second,ms) To set the desired time using local or UTC timing zone
  • 48. JavaScript – Build-in Objects String Object • A collection of characters • It wraps Javascript's string primitive data type with a number of helper methods. • Syntax: var val = new String(string);
  • 49. JavaScript – Build-in Objects String Object Methods Description concat(str) Concatenates the two strings charAt(index_val) Return the character specified by value index_val substring(begin, end) Returns the substring specified by begin and end character toLowerCase() Used to convert all uppercase letters to lowercase toUpperCase() Used to convert all lowercase letters to uppercase valueOf() Returns the value of the string
  • 50. JavaScript – Build-in Objects Boolean Object • Represents two values, either "true" or "false". • If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. the object Methods Description toSource() Returns a string containing the source of the Boolean object toString() Returns a string of either "true" or "false" depending upon the value of valueOf() Returns the primitive value of the Boolean object
  • 51. JavaScript Object – Build-in Objects Window _parent – URL is loaded in parent window Methods Description alert(String) Displays the alert box with some message and OK button confirm(String) Displays the alert box with some message and OK button and Cancel button prompt(String) Displays a dialog box which allows the user to input some data open(URL, width, height) Opens a new window with specified URL _blank – URL is loaded in new window _self – URL replaces currently opened window _top – URL replaces the currently opened frameset close() Close the current window moveBy() Move the window from the current position to some other position moveTo() Moves the window to specific position resizeBy() Resizes the window by the specified pixels resizeTo() Resizes the window by the specified width and height
  • 52. JavaScript – Regular Expression • A regular expression is a special text string that defines the search pattern. • It is a logical expression. • Create a regular expression pattern using forward slash /. • It is a powerful pattern-matching and search-and-replace functions on text. • Syntax: var pat = /pattern/
  • 53. JavaScript – Regular Expression Special Characters Description . Any character expect new line ? 0 or 1 * 0 or more occurrence + 1 or more occurrence ^ Start of the String $ End of the String [abc] Any of the characters a, b, or c [A-Z] Any character from uppercase A to uppercase Z
  • 54. JavaScript – Regular Expression Methods Description exec Tests for a match in a string. If it finds a match, it returns a result array, otherwise it returns null. test Tests for a match in a string. If it finds a match, it returns true, otherwise it returns false. match Tests for a match in a string. It returns an array of information or null on a mismatch. search Tests for a match in a string. It returns the index of the match, or -1 if the search fails. replace Tests for a match in a string and replaces the matched substring with a replacement substring. split Uses the regular expression or a fixed string to break a string into an array of substring.
  • 58. JavaScript – Regular Expression X + 0 Phone Number Checking X 0 Phone Number Checking v 0. c!:J '{:( a K : � � C CD File fVolumes/Kav1ya/Academ1cs/lT2253%20-%20WE/Examples/JavaScript%20Examples/phoneno.html 0 Sci-Hub I The ma e Tamil Jothida Pala ,j Microsoft Teams 0 � AIRCC Publishing � Machine Learning Enter Phone Number: I (333) 5555555 Country Code: 1�3_3 � Phone Number: �5 5_5 � Click
  • 59. JavaScript – Exceptions • Exception handling is a mechanism that handles the runtime errors so that the normal flow of the application can be maintained. Statements: • try: Test a block of code for errors • catch: Handle the error • throw: Create custom errors • finally: Execute code, after try and catch, regardless of the result.
  • 60. JavaScript – Exceptions Syntax try { //Block of code to try } catch(err) { //Block of code to handle errors }
  • 64. JavaScript – Event Handling • Event: An activity that represents a change mouse clicks, key press. in the environment. Example: • Event Handler: A script that gets executed in response to these events. It enables the web document to respond that user activities through the browser window. • Event Registration: The process of connecting even handler to an event. It can be done using two methods: – Assigning the tag attributes – Assigning the handler address to object properties
  • 65. JavaScript – Event Handling Event Description Associated Tags onclick The user clicks an HTML element <a>, <input> ondbclick The user double clicks an HTML element <a>, <input>, <button> onmouseup The user releases the left mouse button Form elements onmousedown The user clicks the left mouse button Form elements onmousemove The user moves the mouse Form elements onmouseover The user moves the mouse over an HTML element Form elements onmouseout The user moves the mouse away from an HTML element Form elements onkeydown The user pushes a keyboard key Form elements onkeyup The user releases a key from keyboard Form elements onkeypress The user presses the key button Form elements
  • 66. JavaScript – Event Handling Event Description Associated Tags onchange An HTML element has been changed <input> <textarea> <select> onsubmit The user clicks the submit button <form> onreset The user clicks the reset button <form> onselect On selection <input>, <textarea> onload After getting the document is loaded <body> onunload The user exits the document <body>
  • 67. JavaScript – Event Handling Syntax: <input type = "button" name = “My_button” onclick = ”display()” /> Tag attribute Event handler
  • 68. JavaScript – Event Handling onclick Event Handling:
  • 69. JavaScript – Event Handling onclick Event Handling:
  • 70. JavaScript – Event Handling onload Event Handling:
  • 71. JavaScript – Event Handling onload Event Handling:
  • 72. JavaScript – Event Handling mouseover and mouseout Event Handling:
  • 73. JavaScript – Event Handling mouseover and mouseout Event Handling:
  • 74. JavaScript – Event Handling keypress Event Handling:
  • 75. JavaScript – Event Handling keypress Event Handling:
  • 76. JavaScript – Validation • Various control objects are placed on the form. • These control objects are called widgets. • These widgets used in JavaScript are Textbox, Radio button, Check box and so on. • In JavaScript, the validation of these widgets is an important task.
  • 77. JavaScript – Validation Create the following HTML form and do the following validation in Java Script. a) Check fields for not Empty b) c) Email ID validation. Numbers and special characters not allowed in First name and Last name.
  • 78. JavaScript – Debuggers • The standard traditional method of debugging the JavaScript is using alert() to display the values of the corresponding variables. • Use API methods for debugging the JavaScript. • Use log() function console API.
  • 79. JavaScript – Debuggers • The standard traditional method of debugging the JavaScript is using alert() to display the values of the corresponding variables. • Use API methods for debugging the JavaScript. • Use log() function console API.
  • 82. JavaScript – Examples 1. Design the simple calculator in JavaScript with the following operations: Addition, Subtraction, Multiplication and Division. Use JavaScript and HTML to create a page with two panes. The first pane (on the 2. left) should have a text area where HTML code can be typed by the user. The pane on the right side should display the preview of the HTML code user, as it would be seen in the browser. Write a JavaScript to get the current hours as h and do the following: If h>=0 and h<12 then print “Good Morning” typed by the 3. If h>=12 and h<4 then print “Good Noon” If h>=4 and h<8 then print “Good Evening” Otherwise print “Good night”