0% found this document useful (0 votes)
5 views131 pages

Javascript

The document discusses the limitations of HTML and CSS, highlighting their static nature and lack of interactivity. It introduces Dynamic HTML (DHTML), which combines HTML, CSS, JavaScript, and the Document Object Model (DOM) to create dynamic web pages. Additionally, it covers JavaScript's features, advantages, data types, and control structures, emphasizing its role in enhancing web interactivity and functionality.

Uploaded by

aashsohail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views131 pages

Javascript

The document discusses the limitations of HTML and CSS, highlighting their static nature and lack of interactivity. It introduces Dynamic HTML (DHTML), which combines HTML, CSS, JavaScript, and the Document Object Model (DOM) to create dynamic web pages. Additionally, it covers JavaScript's features, advantages, data types, and control structures, emphasizing its role in enhancing web interactivity and functionality.

Uploaded by

aashsohail
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

Drawbacks of HTML & CSS

• Is good for publishing only static documents.

• The content cannot be changed once it has been


delivered to the browser .

• Though CSS-2 and CSS-3 have bought in some


interactivity, the scope is limited.

1
Dynamic HTML
DHTML
• Dynamic HTML is not a markup or programming language.

• It is a term that combines the features of various web development technologies


for creating the web pages dynamic and interactive.

• DHTML consists of the following four components or languages:

• HTML

• CSS

• Javascript or VBscript

• DOM (Document Object Model)

• 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.

• It also provides the feature in browsers for data binding.

• 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?

• The term “scripting language” is also used loosely to refer to dynamic


high-level general-purpose languages, such as JavaScript, VBScript,
with the term “script”

• Scripting languages are becoming more popular due to the


emergence of web based applications.
Advantages

• Easy to learn and use

• Minimum programming knowledge or experience required.

• Allow complex tasks to be performed in relatively few steps.

• Allow simple creation and editing in a variety of text editors.

• Allow the addition of dynamic and interactive activates to web pages.

• Editing and running code is fast.


Type of Scripting:

• Scripts are classified into the following two types:

• Client Side Scripts

• Server side Scripts


Introductıon to Javascrıpt
JAVASCRIPT
• JavaScript is designed by Brendan Eich, in 1995

• It is an object oriented scripting language that designed primarily for people


who are building web pages using HTML.

• JavaScript programs are embedded within HTML documents in source code


form

• The script is platform independent and it is interpreted by the browser.

• JavaScript was designed to add interactivity to HTML pages.

 Everyone can use JavaScript without purchasing a license

 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

• It is widely supported in Web Browsers.

• It gives easy access to the document objects and can manipulate


most of them.

• Can be used for animation without download time

• Web surfers don’t need special plugins to use the scripts.

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..

• The script tag takes two important attributes:

• Language − This attribute specifies what scripting language you are


using. Typically, its value will be javascript. Although recent versions
of HTML have phased out the use of this attribute.

• Type − This attribute is what is now recommended to indicate the


scripting language in use and its value should be set to
"text/javascript".
Where to place the JavaScript code?

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 (;).

• Many programmers continue this habit when writing


JavaScript, but in general, semicolons are optional!
However, semicolons are required if you want to put
more than one statement on a single line.
Example

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

• JavaScript is a case-sensitive language.

• This means that the language keywords, variables, function names,


and any other identifiers must always be typed with a consistent
capitalization of letters.

• So the identifiers ‘A’ and ‘a’ will convey different meanings in


JavaScript.
Statements
• In a programming language, these programming instructions are
called statements.

• A JavaScript program is a list of programming statements.

• A statement is a section of JavaScript that can be evaluated by a Web


browser

• A script is simply a collection of statements

• JavaScript statements are composed of: Values, Operators,


Expressions, Keywords, and Comments.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>In HTML, JavaScript statements are executed by the browser.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World.";
</script>
</body>
</html>

This statement tells the browser to write "Hello World." inside an HTML element
with id="demo":
Comments in JavaScript

• JavaScript supports both C-style and C++-style comments,


• Any text between a // and the end of a line is treated as a
comment and is ignored by JavaScript.
• Any text between the characters /* and */ is treated as a
comment. This may span multiple lines.
• JavaScript also recognizes the HTML comment opening
sequence <!--. JavaScript treats this as a single-line comment,
just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by
JavaScript so it should be written as //-->.
Example

<script language = "javascript" type = "text/javascript">


<!--
// This is a comment. It is similar to comments in C++
/*
This is a multi-line comment in JavaScript
It is very similar to comments in C Programming
*/
//-->
</script>
JavaScript Variables

• In javascript variable declaration is implicit.


• Declare a JavaScript variable with the var keyword
• Syntax: var variable_name;
• var x = 5;
• var y = 6;
• var z = x + y;
JavaScript Variable Scope

• The scope of a variable is the region <html>


of your program in which it is <body onload = checkscope();>
defined. <script type = "text/javascript">
• Global Variables − A global variable <!--
has global scope which means it can var myVar = "global";
be defined anywhere in your // Declare a global variable
JavaScript code. function checkscope( ) {
• Local Variables − A local variable will var myVar = "local";
be visible only within a function // Declare a local variable
where it is defined. Function document.write(myVar);
parameters are always local to that }
function. //-->
</script>
</body>
</html>
JavaScript Identifiers
• All JavaScript variables must be identified with unique names.
• These unique names are called identifiers.

• Identifiers can be short names (like x and y) or more descriptive


names (age, sum, totalVolume).

• The general rules for constructing names for variables (unique


identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter.
• Names can also begin with $ and _ (but we will not use it in this tutorial).
• Names are case sensitive (y and Y are different variables).
• Reserved words (like JavaScript keywords) cannot be used as names.
Data Types

• Primitive Data Types


• Numbers
• Strings
• Boolean (True, False)

• Composite Data Types


• Arrays
• Objects
JavaScript Datatypes
• One of the most fundamental characteristics of a programming
language is the set of data types it supports. These are the
type of values that can be represented and manipulated in a
programming language.
• JavaScript allows you to work with three primitive data types −
• Numbers, eg. 123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
• JavaScript also defines two trivial data types,
• Null - something that doesn't exist. In JavaScript, the data type of null
is an object.
• Undefined - variable without a value
• In addition to these primitive data types, JavaScript supports a
composite data type known as object.
JavaScript Types are Dynamic

• JavaScript has dynamic types. This means that the same variable can
be used to hold different data types

var x; // Now x is undefined


x = 5; // Now x is a Number
x = "John"; // Now x is a String
JavaScript Strings

• A string (or a text string) is a series of characters

• Strings are written with quotes

• You can use single or double quotes

var carName1 = ”MI”; // Using double quotes


var carName2 = ’MIT’; // Using single quotes
JavaScript Numbers

• JavaScript has only one type of numbers.

• Numbers can be written with, or without decimals.

var x1 = 34.00; // Written with decimals


var x2 = 34; // Written without decimals
JavaScript Booleans

• Booleans can only have two values: true or false.

var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false
JavaScript Arrays

• JavaScript arrays are written with square brackets.

• Array items are separated by commas.

• The following code declares (creates) an array called cars, containing


three items (car names):
var cars = [“Honda", "Volvo", “Ford"];

• Array indexes are zero-based, which means the first item is [0],
second is [1], and so on.
Creating an Array

• There are several different ways to create an array in JavaScript

• Using the Array() constructor:


var a = new Array(1, 2, 3, 4, 5);
var b = new Array(10);

• Using array literals:


var c = [1, 2, 3, 4, 5];
Accessing Array Elements

• Array elements are accessed using the [ ] operator


• Example:

var colors = [“red”, “green”, “blue”];

console.log(colors[0])
Adding Elements

• To add a new element to an array, simply assign a value to it


• Example:
var colors = [“red”, “green”, “blue”];
colors[3] = 1;
Array Length

• All arrays created in JavaScript have a special length property that


specifies how many elements the array contains

• Example:
var colors = [“red”, “green”, “blue”];
var length = colors.length;
Array Length

• All arrays created in JavaScript have a special length property that


specifies how many elements the array contains

• 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

Operator Example Is The Same As

= 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

== is equal to 5==8 returns false

=== is equal to (checks for both value and type) x=5

y="5"

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true


Logical Operator
Operator Description Example

&& and x=6

y=3

(x < 10 && y > 1) returns true

|| or x=6

y=3

(x==5 || y==5) returns false

! not x=6

y=3

!(x==y) returns true


The typeof Operator
• You can use the JavaScript typeof operator to find the type of a
JavaScript variable.
• The typeof operator returns the type of a variable or an
expression:

typeof "" // Returns "string“

typeof "John" // Returns "string“

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

• There are three basic types of control structures in JavaScript:

• the if statement,

• the while loop, and

• the for loop

• Each control structure manipulates a block of JavaScript expressions


beginning with { and ending with }
JavaScript - if...else Statement
if statement
if (expression) {
• JavaScript supports the
Statement(s) to be executed if expression is true
following forms of }
• if statement
• if...else statement
If… else… statement
• if...else if... statement. if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}

if...else if... statement


if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else {
Statement(s) to be executed if no expression is true
}
Examples

<script type = "text/javascript">


var age = 15;
if( age > 18 ) {
document.write("<b>Qualifies for driving</b>");
}
else {
document.write("<b>Does not qualify for driving</b>");
}
</script>
<script type = "text/javascript">
var book = "maths";
if( book == "history" ) {
document.write("<b>History Book</b>");
} else if( book == "maths" ) {
document.write("<b>Maths Book</b>");
} else if( book == "economics" ) {
document.write("<b>Economics Book</b>");
} else {
document.write("<b>Unknown Book</b>");
}
</script>
Repeat Loops

• A repeat loop is a group of statements that is repeated until a


specified condition is met

• 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 while loop is used count = 0;


to execute a block of
code while a certain while (count <= 10) {
condition is true document.write(count);
count++;
}
The For 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

// Print the numbers 1 i=1 initializes the counter


through 10
i<=10 is the target
for (i=1; i<= 10; i++) value
document.write(i);
i++ updates the
counter at the end
of the loop
Switch Case
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
JavaScript - Functions
• A function is a group of reusable code which can be called
anywhere in your program.
Function Definition
• The most common way to define a function in JavaScript is by using
the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded
by curly braces.
Syntax:
<script type = "text/javascript">
function functionname(parameter-list) {
statements
}
</script>
Example
<script type = "text/javascript">
function sayHello() {
alert("Hello there");
}
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply
need to write the name of that function.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("Hello there!");
}
</script>
</head>

<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

• A JavaScript function can have an optional return statement.


• This is required if you want to return a value from a function.
• This statement should be the last statement in a function.
• For example, you can pass two numbers in a function and then you
can expect the function to return their multiplication in your calling
program.
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last) {
var full;
full = first + last;
return full;
}
function secondFunction() {
var result;
result = concatenate(‘Web', ‘Technologies');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
JavaScript Numbers

• 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

toString() returns a number as a string


toExponential() returns a string, with a number rounded and written using
exponential notation
toFixed() returns a string, with the number written with a specified
number of decimals
toPrecision() returns a string, with a number written with a specified
length
valueOf() returns a number as a number
Number() Returns a number, converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns an integer
String

• A JavaScript string is zero or more characters written inside quotes.


• var x = “ABC DEF";
• var x = ’ABC DEF’;

• strings can also be defined as objects with the keyword new:


• Eg:
• var x = “ABC";
• var y = new String(“ABC");
JavaScript String Methods
length The length property returns the length of a string
indexOf() returns the index of (the position of) the first occurrence of a specified text in a string
lastIndexOf() returns the index of the last occurrence of a specified text in a string
search() searches a string for a specified value and returns the position of the match
slice() extracts a part of a string and returns the extracted part in a new string.
substring() similar to slice(). The difference is that substring() cannot accept negative indexes.
substr() is similar to slice(). The difference is that the second parameter specifies the length of
the extracted part.
replace() method replaces a specified value with another value in a string
toUpperCase() string is converted to upper case
toLowerCase() string is converted to lower case
concat() joins two or more strings
trim() method removes whitespace from both sides of a string
charAt() returns the character at a specified index (position) in a string
charCodeAt() returns the unicode of the character at a specified index in a string
split() string can be converted to an array
Example

var A = ‘This is a string';


b = A.slice(0,5);
c = A.slice(6,9);

console.log(b); //will print “This i”


console.log(c); //will print “ a s “
JavaScript - Events
• JavaScript's interaction with HTML is handled through events
that occur when the user or the browser manipulates a page.

• When the page loads, it is called an event. When the user


clicks a button, that click too is an event. Other examples
include events like pressing any key, closing a window, resizing
a window, etc.

• Developers can use these events to execute JavaScript coded


responses, which cause buttons to close windows, messages to
be displayed to users, data to be validated, and virtually any
other type of response imaginable.
Events
• onclick - This is the most frequently used event type which
occurs when a user clicks the left button of his mouse.

• onsubmit: is an event that occurs when you try to submit a


form. You can put your form validation against this event type.

• onmouseover and onmouseout: onmouseover event triggers


when you bring your mouse over any element and the
onmouseout triggers when you move your mouse out from
that element.
HTML DOM Event Object
Attribute Description W3C
onblur The event occurs when an element loses focus Yes
onchange The event occurs when the content of an element, the selection, or the checked Yes
state have changed

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

• JavaScript supports three important types of dialog boxes. These


dialog boxes can be used to raise and alert, or to get confirmation on
any input or to have a kind of input from the users.
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.

 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

• 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.

• 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();

Boolean Object Methods:


 toString() :Converts a Boolean value to a string, and returns the
result
 valueOf() :Returns the primitive value of a Boolean object

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);

• Number Object Properties


• MAX_VALUE - Returns the largest number possible in JavaScript
• MIN_VALUE - Returns the smallest number possible in JavaScript
• NEGATIVE_INFINITY - Represents negative infinity (returned on
overflow)
• POSITIVE_INFINITY - Represents infinity (returned on overflow)

• Number Object Methods


• toExponential(x) Converts a number into an exponential notation
• toFixed(x) Formats a number with x numbers of digits after the
decimal point
• toPrecision(x) Formats a number to x length
• toString() Converts a Number object to a string
• valueOf() Returns the primitive value of a Number object
Date object
• Syntax:
var d = new Date();

• new Date() // current date and time


• new Date(milliseconds) //milliseconds since 1970/01/01
• new Date(dateString)
• var d = new Date("July 21, 1983 01:15:00");
• new Date(year, month, day, hours, minutes, seconds, milliseconds)
• var d = new Date(1986,07,09,08,17,06,88);

• 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>

• Sat Aug 09 1986 08:17:06 GMT+0530 (India Standard Time)


Date object Methods
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
Returns the number of milliseconds since midnight Jan 1
getTime()
1970, and a specified date
Returns the time difference between UTC time and local
getTimezoneOffset()
time, in minutes

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.

• Method include abs(x), random(),sin(x) etc.

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;

• Pattern specifies the pattern of an expression and modifiers specify if


a search should be global, case-sensitive, etc.

• Regular expressions are used to perform powerful pattern-matching


and "search-and-replace" functions on text.
102
Regular Expressions - Brackets
Expression Description
[abc] Find any character between the brackets

[^abc] Find any character not between the brackets

[0-9] Find any digit from 0 to 9


[A-Z] Find any character from uppercase A to
uppercase Z
[a-z] Find any character from lowercase a to
lowercase z
[A-z] Find any character from uppercase A to
lowercase z
(x|y|z) Find any of the alternatives specified

103
Regular Expressions Metacharacters

104
Regular Expressions - Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{X} Matches any string that contains a sequence of X n's

n{X,Y} Matches any string that contains a sequence of X to Y n's

n{X,} Matches any string that contains a sequence of at least X n's

n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning of it

?=n Matches any string that is followed by a specific string n

?!n Matches any string that is not followed by a specific string 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

test() Tests for a match in a string. Returns true or false

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

• String: “ManipalMIT, MAHEManipal”

Pattern:/\BManipal/
Match: “ManipalMIT, MAHEManipal”

Pattern:/Manipal\B/
Match: “ManipalMIT, MAHEManipal”

Pattern:/Manipal\b/
Match: “ManipalMIT, MAHEManipal”

108
Example

• String: “ManipalMIT, MAHEManipal”

Pattern: /^Manipal.*$/
Match: ManipalMIT, MAHEManipal

109
Example

• 1280x720 , 1920x1600 , 1024x768


• (\d+)x(\d+)
• 1(\d{3})x[7|1](\d){2,3}

• Jan 1987 , May 1969, Aug 2011


• [A-z]{3}\s\d{4}

• 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

• Pattern format : yyyy-mm-dd


• ^(19|20)\d\d[- /](0[1-9]|1[012])[- /](0[1-9]|[12][0-9]|3[01])$

• 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

• JavaScript objects are written with curly braces {}.

• Object properties are written as name:value pairs, separated by


commas.

• var person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"};
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body>
</html>
Try...Catch Statement

• 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

• The throw statement is used to create an exception.

• If you use this statement together with the try...catch statement, the
program flow can be controlled and accurate error messages can be
generated.

• Syntax: throw (exception)

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

• Cookies are data, stored in small text files, on your computer.


• When a web server has sent a web page to a browser, the connection
is shut down, and the server forgets everything about the user.
• Cookies were invented to solve the problem "how to remember
information about the user":
• When a user visits a web page, his/her name can be stored in a
cookie.
• Next time the user visits the page, the cookie "remembers" his/her
name.
• When a browser requests a web page from a server, cookies
belonging to the page are added to the request. This way the server
gets the necessary data to "remember" information about users.
Cookie using JavaScript
JavaScript can create, read, and delete cookies with the
document.cookie property.
You can also add an expiry date (in UTC time). By default, the cookie is
deleted when the browser is closed:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013
12:00:00 UTC; path=/";
HTML Canvas

• 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

• Arrow functions were introduced in ES6.


• Arrow functions allow us to write shorter function syntax

Before: With Arrow Function:


hello = function() { hello = () => {
return "Hello World!"; return "Hello World!";
} }
Arrow function syntax
• The “fat” arrow => was chosen to be compatible with
CoffeeScript, whose fat arrow functions are very similar.
• Specifying parameters:
• () => { ... } // no parameter
• x => { ... } // one parameter, an identifier
• (x, y) => { ... } // several parameters
• Specifying a body:
• x => { return x * x } // block
• x => x * x // expression, equivalent to previous line

You might also like