Javascript Syntax, Types of Javascript, variables, arrays, functions, conditions, loops, Pop up boxes, Javascript objects and DOM, Javascript inbuilt functions, Javascript validations, Regular expressions, Event handling with Javascript, Callbacks in Javascript, Function as arguments in Javascript, ...
Javascript Syntax, Types of Javascript, variables, arrays, functions, conditions, loops, Pop up boxes, Javascript objects and DOM, Javascript inbuilt functions, Javascript validations, Regular expressions, Event handling with Javascript, Callbacks in Javascript, Function as arguments in Javascript, Object concepts in Javascript
Size: 4.87 MB
Language: en
Added: Aug 27, 2022
Slides: 67 pages
Slide Content
Web Development
UNIT - 3
Java Script
Outline....
* JavaScript Syntax
* Types of JavaScript
* Variables
+ Arrays
* Functions
* Conditions
+ Loops
* Pop up boxes
* JavaScript objects and DOM
* JavaScript inbuilt functions
+ JavaScript validations
Outline....
+ Regular expressions
* Event handling with JavaScript
* Callbacks in JavaScript
+ Function as arguments in JavaScript
* Object concepts in JavaScript
Introduction of JavaScript
* JavaScript is one of the most popular interpreted, lightweight, and
compiled programming languages.
+ The programs in JavaScript are called scripts which are executed as plain
texts.
+ We can write these scripts directly on our HTML page or use an external
JavaScript file.
* JavaScript can execute in the browser, and also on the server, or actually on
any device that has a special program called the JavaScript engine.
* JavaScript is used for server-side as well as in client-side developments.
* There are 2 ways to use the JavaScript in the HTML file:
+ Internal JavaScript
+ External JavaScript
Internal JavaScript
+ The JavaScript can be directly embedded within the HTML document or it
can be stored as external file.
* In HTML, JavaScript code is inserted between <script> and </script> tags.
<!DOCTYPE html>
<html>
<body>
<script>
document.write("My First JavaScript");
</script>
</body>
</html>
+ In a programming language, variables are used to store data values.
* JavaScript uses the keywords var, let and const to declare variables.
* An equal sign is used to assign values to variables.
* In this example, x is defined as a variable. Then, x is assigned (given) the
value 6:
* The var keyword is used in all JavaScript code from 1995 to 2015.
* The let and const keywords were added to JavaScript in 2015.
* If you want your code to run in older browser, you must use var.
+ JavaScript supports following comments.
* The //i.e. single line comments can be used in JavaScript.
* The /* and */ can be used as a multi-line comment.
JavaScript Data Types
+ JavaScript define two entities primitives and objects.
+ The primitives are for storing the values where the objects is for storing the
reference to the actual value.
* There are following primitive types used in JavaScript
1. Number
2. String
3. Boolean
4. Undefined
5. Null
» There are three types of predefined object in JavaScript
1. Number
2. String
3. Boolean
JavaScript Data Types
* let x1 = 34.00; // Written with decimals
+ let x2 = 34; // Written without decimals
* let carNamel = "Volvo XC60"; // Using double quotes
* let carName2 = 'Volvo XC60'; // Using single quotes
*(x==y) // Returns true
+ A JavaScript function is a block of code designed to perform a particular
task.
» A JavaScript function is executed when "something" invokes it (calls it).
* You can reuse code: Define the code once, and use it many times.
+ Syntax
function name(parameter1, parameter2) { // code to be executed }
* Function Invocation (calls)
+ When an event occurs (when a user clicks a button)
+ When it is invoked (called) from JavaScript code
+ Automatically (self invoked)
+ Very often when you write code, you want to perform different actions for
different decisions.
* In JavaScript we have the following conditional statements:
+ Use if to specify a block of code to be executed, if a specified condition is
true.
+ Use else to specify a block of code to be executed, if the same condition is
false.
+ Use else if to specify a new condition to test, if the first condition is false.
* Use switch to specify many alternative blocks of code to be executed.
JavaScript Loops
+ Loops are handy, if you want to run the same code over and over again,
each time with a different value.
* JavaScript supports different kinds of loops:
+ for - loops through a block of code a number of times.
+ while - loops through a block of code while a specified condition is true.
+ do/while - also loops through a block of code while a specified condition is
true.
JavaScript Popup Boxes
+ JavaScript has three kind of popup boxes: Alert box, Confirm box, and
Prompt box.
+ Alert Box
+ An alert box is often used if you want to make sure information comes
through to the user.
+ When an alert box pops up, the user will have to click "OK" to proceed.
* Confirm Box
* A confirm box is often used if you want the user to verify or accept
something.
* When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
JavaScript Popup Boxes
» If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
+ Prompt Box
* A prompt box is often used if you want the user to input a value before
entering a page.
* When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
* If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
JavaScript Popup - Alert Box
+ Syntax
alert("sometext");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<script>
alert("l am an alert box!");
</script>
</body>
</html>
JavaScript Popup - Confirm Box
+ Syntax
confirm("sometext");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<script>
var txt=confirm("Press a button!");
if (txt== true) {
document.write("You pressed OK!");
}else {
document.write("You pressed Cancel!");
}
</script>
</body>
</html>
JavaScript Popup - Prompt Box
+ Syntax
prompt("sometext","defaultText");
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt Box</h2>
<script>
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person =="") {
document.write("User cancelled the prompt.");
}else {
document.write("Hello " + person +"! How are you today?");
}
</script>
</body>
</html>
JavaScript objects and DOM
+ With the HTML DOM, JavaScript can access and change all the elements of
an HTML document.
+ When a web page is loaded, the browser creates a Document Object
Model of the page.
* The HTML DOM model is constructed as a tree of Objects:
Document
Root element:
<html>
I
1
Element Element:
<head> <body>
Element? Zerbure: Element: Element:
<title> “href” <a> <hi>
Text: Texte Text
sty title” My link” “My header”
JavaScript objects and DOM
+ With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
+ JavaScript can change all the HTML elements in the page.
* JavaScript can change all the HTML attributes in the page.
+ JavaScript can change all the CSS styles in the page.
+ JavaScript can remove existing HTML elements and attributes.
« JavaScript can add new HTML elements and attributes.
+ JavaScript can react to all existing HTML events in the page.
+ JavaScript can create new HTML events in the page.
JavaScript objects and DOM
* What is the DOM?
* The DOM is a W3C (World Wide Web Consortium) standard.
» "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."
+ 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.
+ HTMLDOM - standard model for HTML documents.
JavaScript objects and DOM
+ What is the HTML DOM?
+ The HTML DOM is a standard object model and programming interface for
HTML. It defines:
* The HTML elements 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.
JavaScript HTML DOM Methods
+ 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).
JavaScript HTML DOM Methods
Method | Meaning |
This method is used to obtain the specific element which is
cli specify by some id within the script.
createElelement This method is used to create an element node.
createTextNode Useful for creating a text node.
createAttribute Useful for creating attribute.
appendChild For adding a new child to specified node, this method is used.
removeChild For removing a new child to specified node, this method is used.
getAttribute This method is useful for returning the specified attribute value.
This method is useful for setting or changing the specified
setAttribute attribute to the specified value.
JavaScript HTML DOM Properties
Property
attributes This property is used to get the attribute nodes of the node.
cade This DOM property is useful for obtaining the parent node of the
specific node.
tete This DOM property is useful for obtaining the child nodes of the
specific node.
innerHTML It is useful for getting the text value of a node.
* In the example above, getElementByld is a method, while innerHTML is a
property.
Modifying — Appending an Elements using DOM
<!DOCTYPE html>
<html>
<body>
<div id="div1”>
<p id=“p1">The 1° sentence in HTML</p>
<p id=“p2">The 24 sentence in HTML</p>
</div>
<script>
var pnode = document.createElement(“p”);
var node = document.createTextNode(“Newly sentence”);
pnode.appendChild(node);
var element = document.getElementByld(“div1”);
element.appendChild(pnode);
</script>
</body>
</html>
Modifying — Inserting an Elements using DOM
<!DOCTYPE html>
<html>
<body>
<div id="div1”>
<p id=“p1">The 1° sentence in HTML</p>
<p id=“p2">The 24 sentence in HTML</p>
</div>
<script>
var pnode = document.createElement(“p”);
var node = document.createTextNode(“Newly sentence”);
pnode.appendChild(node);
var element = document.getElementByld(“div1”);
var nextnode = document.getElementByld(“p2”);
element.insertBefore(pnode,nextnode);
</script>
</body>
</html>
Modifying — Removing an Elements using DOM
<!DOCTYPE html>
<html>
<body>
<div id="div1”>
<p id=“p1">The 1° sentence in HTML</p>
<p id=“p2">The 24 sentence in HTML</p>
<p id="p3">The 3 sentence in HTML</p>
</div>
<script>
var pnode = document.getElementByld(“div1”);
var node = document.getElementByld(“p2”);
pnode.removeChild(node);
</script>
</body>
</html>
JavaScript In-built Functions
+ Global functions are the top-level function in JavaScript that are
independent of any specific object.
* These functions uses the built-in object of the JavaScript.
* The Following are some global functions:
* encodeURI(URL)
* decodeURI(URL)
* parselnt(string,redix)
« eval(string)
JavaScript In-built Functions - encodeURI(URL)
+ This function is used to encode the URL. This function encodes special
characters, except:,/?:@&=+S#.
<!DOCTYPE html>
<html>
<body>
<script>
var uri = “my example.jsp?name=< >ggg”;
document.write(encodeURI(uri) + “<br />”);
</script>
</body>
</html>
JavaScript In-built Functions - decodeURI(URL)
<!DOCTYPE html>
<html>
<body>
<script>
var uri = “my example.jsp?name=< >ggg”;
var en_uri = encodeURI(uri);
document.write((en_uri)+"<br />");
document.write(decodeURI(en_uri));
</script>
</body>
</html>
JavaScript In-built Functions - parselnt()
+» This function parse a string and return the integer value.
+» A radix parameter specifies the number system to use:
+ 2= binary, 8 = octal, 10 = decimal, 16 = hexadecimal.
+ It is important to validate the form submitted by the user because it can
have inappropriate values. So, validation is must to authenticate user.
* JavaScript provides facility to validate the form on the client-side so data
processing will be faster than server-side validation.
* Through JavaScript, we can validate name, password, email, date, mobile
numbers and more fields.
JavaScript Validation — Blank Form
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.myForm.fname.value;
if (x==""){
alert("Name must be filled out");
return false;
}
}
</script>
</head>
+ Regular Expression is a special text string that defines the search pattern. It
is a logical expression.
* We can create a regular expression pattern using forward slash /.
+ The regular expression is used to do pattern-matching "search-and-
replace" functions on text.
* The words of regular expression are called special character.
JavaScript Regular Expression
Special Character Meaning
Any character except newline
A The character a
ab The string ab
a\b aorb
ar 0 or more a's
\ Escapes a special character
[ab-d] One character of: a,b,c,d
\w Find a word character
\w Find a non-word character
\d Finda digit
\D Find a non-digit character
JavaScript Regular Expression
Special Character
[*ab-d] Find any character except: a,b,c,d
\s Find a whitespace character
\s Find a non-whitespace character
ot Matches any string that containsat least one n
ne Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
mix Matches any string that containsa sequence of Xn's
nf{XY} Matches any string that containsa sequence of X to Y n's
mx} Matches any string that containsa sequence of at least X n's
An Matches any string with n at the beginning of it
\o Null character
Met
exec
test
match
matchAll
search
replace
split
JavaScript Regular Expression
Description
A RegExp method that executes a search for a match in a string. It return an array of
information or null on a mismatch.
A RegExp method that tests for a match in a string. It return true or false.
A string method that executes a search for a match in a string. It return an array of
information or null on a mismatch.
A string method that return an iteration containing all of the matches, including capturing
groups.
A string method that test for a match in a string. It return the index of match or -1 if the
search fails.
A string method that executes a search for a match in a string and replaces the matched
substring with a replacement substring.
A string method that uses a regular expression or a fixed string to break a string into an array
of substrings.
Event handling with JavaScript
* Event is an activity that represents a change in the environment. For
example mouse clicks, pressing a particular key of keyboard represent the
event.
* Event handler is a script that gets executed in response to these events.
Thus event handler enables the web document to respond the user
activities through the browser window.
* JavaScript support this special type of programming in which events may
occurs and these event gets responded by executing the event handlers.
This type of programming is called event-driven programming.
* Events are specified in lowercase letters and these are case-sensitive.
When user double clicksthe mouse button
When user acquires the input focus.
When user release the key from the keyboard
When user presses the key down
When user pressed the key
When user clicks the left mouse button
When user releases the left mouse button
When user moves the mouse
When the user moves the mouse away over some element
Different types of Event
EEE Meaning
mouseover onmouseover When the user moves the mouse away over some element
load onload After getting the document loaded
reset onreset When the reset button is clicked
submit onsubmit When the submit button is clicked
select onselect On selection
unload onunload When user exits the document
Callbacks in JavaScript
+» In JavaScript functions are object. We can pass objects to the function as a
parameter. That means we can pass function as a parameter to another
function.
* The mechanism of passing function as a parameter to another function is
called callback.
Callbacks in JavaScript
<!DOCTYPE html>
<html>
<head>
<script>
function mul(a,b,callback)
{
ans=a*b;
document.write(“The Result is: “ + ans);
callback();
}
function display()
{
document.write(“<br /> See you ..!!”);
ti
</script>
</head>
<body>
<script>
mul(5,4,display);
</script>
</body>
</html>
Function as Argument in JavaScript
+ We can pass a function as a argument to another function in the same way
as a variable is passed as an argument.
<!DOCTYPE html>
<html>
</html>
<body>
</body>
Callbacks in JavaScript
<p> Passing function as a arguments </p>
<button onclick=“OuterFunction(InnerFunction)”> Click Here </button>
<script>
function InnerFunction(value)
\ return “Welcome to JavaScript”;
a OuterFunction(func)
‘ alert(func());
</script> !
Object Concept in JavaScript
+ In JavaScript object is a collection of properties. These properties are
nothing but the members of the classes from Java. For instance in
JavaScript the object Date() is used which member of the class in Java.
+ Some of the well know objects are:
* Math Object
* Number Object
* Date Object
* Boolean Object
* String Object
Math Object in JavaScript
+ For performing the mathematical computations there are some useful
methods available from math object
Method | Meaning
abs(x) Returns the absolute value of x
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (xis in radians)
explx) Returns the value of E"
floor(x) Returns x, rounded downwardsto the nearest integer
log(x] Returns the natural logarithm (base E) of x
maxlx, y, Z, ....n) Returns the number with the highest value
min(x, y, 2, .... n) Returns the number with the lowest value
pow(x, y) Returns the value of x to the power of y
sin) Returns the sine of x (x is in radians)
Math Object in JavaScript
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Math</h1>
<p>Return the numbers with the highest value:</p>
<p id="demo"></p>
<script>
let a = Math.max(5, 10);
let b = Math.max(0, 150, 30, 20, 38);
let c = Math.max(-5, 10);
let d = Math.max(-5, -10);
let e = Math.max(1.5, 2.5);
document.getElementByld("demo").innerHTML = a + "<br>" + b + "<br>" + c+ "<br>" + d +
"<br>" te;
</script>
</body>
</html>
Number Object in JavaScript
+ Number methods help you work with numbers.
Method Meaning
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
POSITIVE_INFINITY Represents infinity (returned on overflow)
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
Number Object in JavaScript
<!DOCTYPE html>
<html>
<body>
<h1> JavaScript Number Properties </h1>
<p> MIN_VALUE returns the smallest number possible in JavaScript. </p>
<p id="demo"></p>
<script>
let x = Number.MIN_VALUE;
document.getElementByld("demo").innerHTML = x;
</script>
</body>
</html>
Date Object in JavaScript
+ These methods can be used for getting information from a date object:
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the mi
second (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Getthetime. ECMAScript5.
Date Object in JavaScript
+ These methods can be used for getting information from a date object:
Method Meaning
getUTCDate() Same as getDate(), but returns the UTC date
getUTCDay() Same as getDay(), but returns the UTC day
getUTCFullYear() Same as getFullYear(), but returns the UTC year
getUTCHours() Same as getHours(), but returns the UTC hour
getUTCMilliseconds() Same as getMilliseconds(), but returns the UTC milliseconds
getUTCMinutes() Same as getMinutes(), but returns the UTC minutes
getUTCMonth() Same as getMonth(), but returns the UTC month
getUTCSeconds() Same as getSeconds(), but returns the UTC seconds
let letter = text1.charAt(0);
let match = result.match("ea'
let substr = result.substr(1, 4);
document.getElementByld("result").innerHTML= result;
document.getElementByld("letter").innerHTML = letter;
document.getElementByld("match").innerHTML= match;
document.getElementByld("substr").innerHTML= substr;
</script>
</body>