Javascript
Javascript
1
Dynamic HTML
DHTML
• Dynamic HTML is not a markup or programming language.
• HTML
• CSS
• Javascript or VBscript
• It is mainly used for defining the objects and properties of all elements in HTML.
3
Features of DHTML
• Its simplest and main feature is that we can create the web page dynamically.
• Dynamic Style is a feature, that allows the users to alter the font, size, color, and
content of a web page.
• It provides the facility for using the events, methods, and properties. And, also
provides the feature of code reusability.
• Using DHTML, users can easily create dynamic fonts for their web sites or web
pages.
• With the help of DHTML, users can easily change the html element’s properties.
• The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.
4
Introduction to Scripting
Script
• What is Script?
Many HTML editors supply a library of common code that can be adapted
and used in pages.
What can JavaScript Do?
• JavaScript gives HTML designers a programming tool - but JavaScript is a scripting
language with a very simple syntax!
• 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.
• JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer
13
Advantages of using JavaScript
14
Where to place the JavaScript code?
Scripts in the body section: Scripts to be executed when the page loads go in the body
section. When you place a script in the body section it generates the content of the
page.
<html>
<body>
<p> All the contents of the page </p>
<script language = "javascript" type = "text/javascript"> document.write("Hello
World!");
</script>
</body>
</html>
Cont..
Scripts in the head section: Scripts to be executed when they are called, or when an
event is triggered, go in the head section.
<html>
<head>
<script type = "text/javascript">
document.write("Hello World!");
</script>
</head>
<body>
</body>
</html>
Where to place the JavaScript code?
Using an External JavaScript
To run the same JavaScript on several pages, without having to write the same script
on every page.
<html>
<head>
<script src=“filename.js”> ……. </script>
</head>
<body>
</body>
</html>
Ending Statements With a
Semicolon?
• With traditional programming languages, like C++ and
Java, each code statement has to end with a
semicolon (;).
Optional Mandatory
<script language = "javascript" <script language = "javascript"
type = "text/javascript"> type = "text/javascript">
var1 = 10 var1 = 10; var2 = 20;
var2 = 20
</script>
</script>
Case Sensitivity
This statement tells the browser to write "Hello World." inside an HTML element
with id="demo":
Comments in JavaScript
• JavaScript has dynamic types. This means that the same variable can
be used to hold different data types
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false
JavaScript Arrays
• Array indexes are zero-based, which means the first item is [0],
second is [1], and so on.
Creating an Array
console.log(colors[0])
Adding Elements
• Example:
var colors = [“red”, “green”, “blue”];
var length = colors.length;
Array Length
• Example:
var colors = [“red”, “green”, “blue”];
var length = colors.length;
JavaScript Operators
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division 5%2 1
remainder)
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Assignment Operator
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
Compare Operator
Operator Description Example
y="5"
y=3
|| or x=6
y=3
! not x=6
y=3
var a = 10;
typeof a //Returns “number”
var a;
typeof a //Returns undefined
Escape sequences
• \b Backspace
• \f Form Feed
• \n New Line
• \r Carriage Return
• \t Horizontal Tabulator
• \v Vertical Tabulator
• \' Single quote
• \" Double quote
• \\ Backslash
Control Structures
• the if statement,
• Repeat loops are very powerful programming tools; They allow for
more efficient program design and are ideally suited for working with
arrays
The While Loop
• The for loop is used when there is a need to have a counter of some
kind
• The counter is initialized before the loop starts, tested after each
iteration to see if it is below a target value, and finally updated at the
end of the loop
Example: For Loop
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Function Parameters
• Till now, we have seen functions without parameters.
• We can pass different parameters while calling a function.
• These passed parameters can be captured inside the function
and any manipulation can be done over those parameters.
• A function can take multiple parameters separated by comma.
<html>
<head>
<script type = "text/javascript">
function sayHello(name, age) {
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello(‘ABC', 7)" value = "Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
return Statement
• var x = "10";
var y = "20";
var z = x + y; // z will be 1020 (a string)
• var x = 10;
var y = "20";
var z = x + y; // z will be 1020 (a string)
• var x = "10";
var y = 20;
var z = x + y; // z will be 1020 (a string)
JavaScript Number Methods
onclick The event occurs when the user clicks on an element Yes
ondblclick The event occurs when the user double-clicks on an element Yes
onerror The event occurs when an error occurs while loading an external file Yes
onfocus The event occurs when an element gets focus Yes
onkeydown The event occurs when the user is pressing a key or holding down a key Yes
onkeypress The event occurs when the user is pressing a key or holding down a key Yes
onkeyup The event occurs when a keyboard key is released Yes
onload The event occurs when an object has been loaded Yes
onmousedown The event occurs when a user presses a mouse button over an element Yes
onmousemove The event occurs when a user moves the mouse pointer over an element Yes
onmouseout The event occurs when a user moves the mouse pointer out of an element Yes
onmouseover The event occurs when a user mouse over an element Yes
onmouseup The event occurs when a user releases a mouse button over an element Yes
onresize The event occurs when the size of an element has changed Yes
onselect The event occurs after some text has been selected in an element Yes
onunload The event occurs before the browser closes the document Yes
71
<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello"
/>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<style>
input:required {
background-color: yellow;}
</style>
<body>
<form>
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
Customized validation
<html><head><script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") { alert("Name must be filled out"); return false;
} return true;
}
</script></head> <body>
<form name="myForm" action=“processdata“ onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form></body>
</html>
Type check
<html>
<body>
<script>
var x = "John"; // x is a string
var y = new String("John"); // y is an object
if(x===y)
alert("equal");
else alert("Not equal");
</script>
</body>
</html>
Document. forms
1. <form id=“form1”>
< input type=“text” id =“t1” />
• Document.forms.namedItem(“form1").innerHTML;
2. document.forms.item(0).id;
3. document.forms[0].id;
<html>
<body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
txt=document.getElementById("intro").innerHTML;
document.write("<p>The text from the intro paragraph: " + txt +
"</p>");
</script>
</body>
</html>
<html>
< body>
< p id="p1">Hello World!</p>
< script>
document.getElementById("p1").innerHTML="New text!";
< /script>
< /body>
< /html>
<html>
<title>Illustrate the use of getElementByID</title>
<body>
<p id="intro">Example</p>
<div id="main">
<p id="main1">The DOM is very useful</p>
<p id="main2">This example demonstrates how to use the <b>getElementById</b>
method</p>
</div>
<script type="text/javascript">
x=document.getElementById("intro");
document.write("Intro paragraph text: " + x.innerHTML);
</script>
</body>
</html>
<html>
<body id="body1">
<p>Hello World!</p>
<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>
<script language="javascript" type="text/javascript">
var x=document.getElementById("body1");
var y=x.getElementsByTagName("p");
for(var ii=0;ii<y.length;ii++)
document.write(y[ii].innerHTML +"<br/>");
</script>
</body>
</html>
Creating new element or node
<html>
<style>
.pstyle{
color:blue;
text-align:right; }
</style>
<body>
<div id="div1"><p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
para.className="pstyle";
var element=document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
Creating new element before existing element
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
var child=document.getElementById("p1");
element.insertBefore(para,child);
</script>
</body>
</html>
Replacing an element
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
parent.replaceChild(para,child);
</script>
</body>
</html>
Removing existing HTML Elements
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
</body>
</html>
<html>
<head>
<title>Attributes example</title>
<script type="text/javascript">
function listAttributes() {
var paragraph = document.getElementById("paragraph");
var result = document.getElementById("result");
if (paragraph.hasAttributes()) {
var attrs = paragraph.attributes;
var output = "";
for(var i = attrs.length - 1; i >= 0; i--) {
output += attrs[i].nodeName + "->" + attrs[i].nodeValue;}
result.innerText = output;
} else {
result.innerText = "No attributes to show"; } }
</script>
</head>
<body>
<p id="paragraph" style="color: green;">Sample Paragraph</p>
<input type="button" value="Show first attribute name and value"
onclick="listAttributes();">
<p id="result"></p></body>
</html>
JavaScript - Dialog Boxes
When an alert box pops up, the user will have to click "OK" to
proceed.
Syntax : alert("sometext");
87
Alert box example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form> <input type="button" value="Click me!" onclick="displaymessage()" >
</form>
</body>
</html>
88
Confirm box
• When a confirm box pops up, the user will have to click
either "OK" or "Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
• Syntax: confirm("sometext");
89
Confirm Box example
<html> <body>
<head> <input type="button"
<script type="text/javascript"> onclick="disp_confirm()"
function disp_confirm() value="Display a confirm box" />
{ </body>
var r=confirm("Press a button"); </html>
if (r==true)
{
document.write("You pressed OK!");
}
else
{
document.write("You pressed Cancel!");
}
}
</script>
</head>
90
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 the input value. If the user clicks
"Cancel" the box returns null.
• Syntax: prompt("sometext","defaultvalue");
91
Prompt Box example
</head>
<html>
<body>
<head>
<input type="button"
<script type="text/javascript"> onclick="disp_prompt()"
function disp_prompt() value="Display a prompt box" />
{ </body>
var name=prompt("Please enter your </html>
name","");
if (name!=null && name!=“” )
{
document.write("Hello " + name + "! How
are you today?");
}
}
</script>
92
Useful objects included in Javascript
• Array
• String
• Boolean
• Number
• Date
• Math
Boolean object
Syntax:
var myBoolean=new Boolean();
Note:
If the Boolean object has no initial value, or if the passed value is one
of the following: 0, -0, null, "“, false, undefined, NaN
Then the object it is set to false.
Else for any other value it is set to true (even with the string
"false")!
Number object
• Syntax:
var num = new Number(value);
• Methods
• date(),
• getDay(),
• getMonth(),
• getTime(),
• setDate()
Date object
• Example 1:
To set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,2,7);
• Example 2:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
• Example 3:
var myDate=new Date();
myDate.setFullYear(2015,2,14);
var today = new Date();
if (myDate>today)
{ document.write("Today is before 14th January 2015"); }
else
{ document.write("Today is after 14th January 2015"); }
Date object
• Example 4:
<html>
<head><script>
function myFunction() {
var d = new Date(1986,07,09,08,17,06,88);
document.getElementById("demo").innerHTML = d.toString();
}</script></head>
<body>
<p>Click the button to display the date.</p>
<input type="button" onclick="myFunction()">Click</button>
<p id="demo"></p>
</body>
</html>
99
Date object Methods
Returns the day of the month, according to universal
getUTCDate()
time (from 1-31)
Returns the day of the week, according to universal
getUTCDay()
time (from 0-6)
Returns the year, according to universal time (four
getUTCFullYear()
digits)
Returns the hour, according to universal time (from
getUTCHours()
0-23)
getUTCMillisecon Returns the milliseconds, according to universal time
ds() (from 0-999)
Returns the minutes, according to universal time
getUTCMinutes()
(from 0-59)
Returns the month, according to universal time (from
getUTCMonth()
0-11)
Returns the seconds, according to universal time
getUTCSeconds()
(from 0-59)
100
Math Object
• The Math object allows you to perform common mathematical tasks.
• Math is not a constructor. All properties and methods of Math can be called by
using Math as an object without creating it.
Ex : var pivalue=Math.PI;
var sqrt_value=Math.sqrt(16);
document.write(Math.round(4.7));
101
RegExp Object
• A regular expression is an object that describes a pattern of characters.
• When you search in a text, you can use a pattern to describe what you
are searching for.
• Syntax:
var patt=new RegExp(pattern,modifiers);
OR
var patt=/pattern/modifiers;
103
Regular Expressions Metacharacters
104
Regular Expressions - Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n
105
Regular Expression – Modifier and methods
Property Description
global Specifies if the "g" modifier is set
ignoreCase Specifies if the "i" modifier is set
multiline Specifies if the "m" modifier is set
Method Description
exec() Tests for a match in a string. Returns the first match
106
Example
• [hc]?at matches:
• "at", "hat", and "cat".
• [hc]*at matches:
• "at", "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on.
• [hc]+at matches:
• "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on, but not "at".
• cat|dog matches:
• "cat" or "dog".
107
Example
Pattern:/\BManipal/
Match: “ManipalMIT, MAHEManipal”
Pattern:/Manipal\B/
Match: “ManipalMIT, MAHEManipal”
Pattern:/Manipal\b/
Match: “ManipalMIT, MAHEManipal”
108
Example
Pattern: /^Manipal.*$/
Match: ManipalMIT, MAHEManipal
109
Example
• file_record_transcript.pdf, file_07241999.pdf
(file_.+)\.pdf$
110
Examples
Number range
1. 000..255
• ^([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$
2. 1..999
• ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])
3. 0 or 000..999
• ^[0-9]{1,3}$
111
Example
• All MasterCard numbers start with the numbers 51 through 55. All
have 16 digits.
• ^5[1-5][0-9]{14}$
• Email
• \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
112
Example on modifier “m”
• String: “ManipalMIT, MAHE Manipal
Manipal
MAHE
manipal”
• Pattern: /^Manipal/mig
• Match: ManipalMIT,
MAHE Manipal
Manipal MAHE
manipal
• The m modifier treat beginning (^) and end ($) characters to match the beginning or
end of each line of a string (delimited by \n or \r)
• Rather than just the beginning or end of the string.
• The m modifier is case-sensitive and will stop the search after the first match
• To perform a global, case-insensitive, multiline search, use this modifier together with
"g" and “i”
Example 1
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = “1999-09-31";
var patt1 = /^(19|20)\d\d[- /](0[1-9]|1[012])[- /](0[1-9]|[12][0-
9]|3[01])$/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
114
Example 2
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") { alert("Name must be filled out"); return false;
} return true;
}
</script>
</head>
<body>
<form name="myForm" action=“processdata“ onsubmit="return validateForm()"
method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
115
JavaScript Objects datatype
• The try...catch statement allows you to test a block of code for errors.
• The try block contains the code to be run
• The catch block contains the code to be executed if an error occurs.
• Syntax
Try
{ //Run some code here }
catch(err)
{ //Handle errors here }
118
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Error Handling</h2>
<p>How to use <b>catch</b> to display an error.</p>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(e) {
document.getElementById("demo").innerHTML = e.message;
}
</script>
</body>
</html>
119
The Throw Statement
• If you use this statement together with the try...catch statement, the
program flow can be controlled and accurate error messages can be
generated.
120
Try Catch with throw
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{
if(x>10)
throw "Err1";
else if(x<0)
throw "Err2";
}
catch(er)
{
if(er=="Err1")
alert("Error! The value is too high");
if(er == "Err2")
alert("Error! The value is too low");
}
</script>
</body>
</html> 121
The onerror Event
The onerror event is fired whenever there is a script error in
the page.
To use the onerror event, you must create a function to
handle the errors.
Then you call the function with the onerror event handler.
<html>
<body>
<img src="image.gif" onerror="myFunction()">
<script>
function myFunction() {
alert('The image could not be loaded.’);
}
</script>
</body>
</html> 122
Cookie
• The HTML <canvas> element is used to draw graphics, on the fly, via
JavaScript.
• Canvas has several methods for drawing paths, boxes, circles, text,
and adding images.
Event Object
• All event objects in the DOM are based on the Event Object.
• Therefore, all other event objects
(like MouseEvent and KeyboardEvent) has access to the Event
Object's properties and methods.
https://developer.mozilla.org/en-US/docs/Web/API/Event
Modern Javascript Essentials
let and const
• ECMAScript 2015
• ES2015 introduced two important new JavaScript keywords: let and
const.
• Before ES2015, JavaScript had only two types of scope: Global
Scope and Function Scope.
• Global Scope: Variables declared Globally (outside any function) have
Global Scope.
• Function Scope: Variables declared Locally (inside a function) have
Function Scope.
• JavaScript Block Scope
• Variables declared with the var keyword cannot have Block Scope.
• Variables declared inside a block {} can be accessed from outside the
block.
const
• Variables defined with const behave like let variables, except
they cannot be reassigned
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
• Declaring a variable with const is similar to let when it comes
to Block Scope.
• The keyword const is a little misleading.
• It does NOT define a constant value. It defines a constant reference
to a value.
• Because of this, we cannot change constant primitive values, but we
can change the properties of constant objects.
JavaScript this keyword
• The JavaScript this keyword refers to the object it belongs to.
• In an object method, this refers to the "owner" of the method.
• In the example, this refers to the person object.
• The person object is the owner of the fullName method.
let person = {
firstName: "Akshay",
lastName : "Kumar",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
JavaScript Arrow Function