SlideShare a Scribd company logo
1 of 120
Department of ISE
WEB TECHNOLOGY
Unit 4
Basics of JavaScript
Dr. CHAYAPATHI A R
Assistant Professor
BMSCE, Bangalore
Department of ISE
Module 3:
Overview of JavaScript, The <script> tag, Document Object
Model (DOM) General Syntactic Characteristics, Primitives,
variables, usage of let and var, typeof operator, Operations,
expressions, == and === operator differences, Screen output and
keyboard input, Control statements, Arrays, strings, string
methods, Objects, Regular Expressions, functions.
Department of ISE
What is JavaScript and What can it do?
• JavaScript is an object-oriented, dynamically typed, client-
side scripting language.
• Although it contains the word Java, JavaScript and Java are
vastly different programming languages with different uses.
• Java is a full-fledged compiled, object oriented language,
popular for its ability to run on any platform with a Java Virtual
Machine installed.
• Where as JavaScript is one of the world’s most popular
languages, with fewer of the object-oriented features of Java,
and runs directly inside the browser, without the need for the
JVM.
Department of ISE
• JavaScript was introduced by Netscape in their Navigator
browser back in 1996.
• It was originally called LiveScript.
• JavaScript is in fact an implementation of a standardized scripting
language called ECMAScript.
• Internet Explorer (IE) at first did not support JavaScript, but
instead had its own browser-based scripting language
(VBScript). While IE now does support JavaScript.
• Microsoft sometimes refers to it as JScript, primarily for
trademark reasons (Oracle currently owns the trademark for
JavaScript).
Department of ISE
• JavaScript is dynamically typed (also called weakly typed) in
that variables can be easily (or implicitly) converted from one
data type to another.
• The type of data a variable can hold is assigned at runtime and
can change during run time as well.
JavaScript can be divided into three parts:
The core javascript
Client side javascript
Server side javascrip
The core is the heart of the language, including its operators, expressions, statements
and subprograms.
Client side JavaScript is a collection of objects that support control of a browser and
interaction with users
For example
With JavaScript, an XHTML document can be made to be responsive to user inputs such
as mouse clicks and keyboard use.
Server-side JavaScript is a collection of objects that make the language useful on a Web
Server;
For example:To support communication with a database management system.
Department of ISE
Client-Side Scripting
- It refers to the client machine (i.e., the browser) running code
locally rather than relying on the server to execute code and
return the result.
Downloading and executing a client-side JavaScript script
Department of ISE
• Advantages of client-side scripting
1. Processing can be offloaded from the server to client machines,
thereby reducing the load on the server.
2. The browser can respond more rapidly to user events than a
request to a remote server ever could, which improves the user
experience.
3. JavaScript can interact with the downloaded HTML in a way that
the server cannot, creating a user experience more like desktop
software.
Department of ISE
• Disadvantages of client-side scripting
1. There is no guarantee that the client has JavaScript enabled
2. The idiosyncrasies between various browsers and operating
systems make it difficult to test for all potential client
configurations. What works in one browser, may generate an
error in another.
3. JavaScript-heavy web applications can be complicated to debug
and maintain.
Department of ISE
JavaScript in Modern Times (AJAX)
• Earlier (in 1998) JavaScript was only slightly useful, and quite
often, had only a few common uses: graphic roll-overs (that
is, swapping one image for another when the user hovered the
mouse over an image), pop-up alert messages, scrolling text
in the status bar, opening new browser windows, and
prevalidating user data in online forms.
• JavaScript became a much more important part of web
development in the mid 2000s with AJAX.
• AJAX : means Asynchronous JavaScript And XML.
Department of ISE
• AJAX refers to a style of website development that makes use
of JavaScript to create more responsive user experience and
also it helps to create asynchronous web applications.
• The most important feature of AJAX sites is the asynchronous
data requests. (not blocking client or browser)
Department of ISE
JavaScript and Java
JavaScript is not an object-oriented programming language. Rather, it is an object-
based language. JavaScript does not have classes. Its objects serve both as objects
and as models of objects. JavaScript it support class-based inheritance, like a
technique called prototype object, thus , this form of inheritance is called prototype-
based inheritance.
Department of ISE
JavaScript Objects:
In JavaScript, objects are collections of properties (Properties are the values
associated with an object),
Which corresponds to the members of classes in Java and C++. For
example:
In the following example we are using the length property of the String object
to return the number of characters in a string
var txt="Hello World!";
document.write(txt.length);
Each property is either a data property or a function or method property.
Data properties appear in two categories: primitive values and references to
other objects.
( In JavaScript, variables that refer to objects are often called objects rather than
references.)
Methods Methods are the actions that can be performed on objects. In the following
example we are using the toUpperCase() method of the String object to display a text in
uppercase letters:
<script type="text/javascript">
var str="Hello world!";
document.write(str.toUpperCase());
</script>
Department of ISE
General Syntactic Characteristics
JavaScript scripts will be embedded in HTML documents
•Either directly, as in
<script type = "text/javaScript">
-- JavaScript script -
</script>
•Or indirectly, as a file specified in the src attribute of <script>, as in
<script type = "text/javaScript“ src = "myScript.js">
</script>
Department of ISE
Where Does JavaScript Go?
• JavaScript can be linked to an HTML page in a number of
ways.
1. Inline
2. Embedded
3. External
• Among these 3 methods external is the preferred method for
cleanliness and ease of maintenance.
• Running JavaScript scripts in browser requires downloading
the JavaScript code to the browser and then running it.
Department of ISE
• Pages with lots of scripts could potentially run slowly,
resulting in a degraded experience while users wait for the
page to load.
• Different browsers manage the downloading and loading of
scripts in different ways.
Department of ISE
Inline JavaScript
• Inline JavaScript refers to including JavaScript code directly
within certain HTML attributes.
• Inline method in general a bad practice and should be avoided.
• In fact, inline JavaScript is much worse than inline CSS.
• Inline JavaScript is a real maintenance nightmare, requiring to
scan through almost every line of HTML looking for your
inline JavaScript.
Department of ISE
Embedded JavaScript
• Embedded JavaScript refers to the placing JavaScript code
within a <script> Element.
• Embedded JavaScript can be used for quick testing and for
learning scenarios, but it is also difficult to maintain like inline
method.
Department of ISE
External JavaScript
• It is advantageous to separate the HTML and JavaScript into
two different files.
• JavaScript supports this separation by allowing links to an
external file that contains the JavaScript.
• This is the recommended way of including JavaScript
scripts in your HTML pages.
Department of ISE
• JavaScript external files have the extension .js
• The link to the external JavaScript file can be placed within the
<head> element, or within the <body> element.
• The advantage of placing external scripts at the bottom of the
<body> can increase the performance.
• A JavaScript file has to be loaded completely before the
browser can begin any other downloads, For sites with multiple
external JavaScript files, this can cause delay in initial page
rendering.
Department of ISE
• Similarly, if the page is loading a third-party JavaScript
library from an external site, and that site becomes
unavailable or especially slow, then your pages will be
rendered especially slow.
Department of ISE
JavaScript Syntax
• Most common programming constructs including variables,
assignment, conditionals, loops, and arrays before moving on
to advanced topics such as events and classes.
JavaScript’s features.
• Everything is type sensitive, including function, class, and
variable names.
• The scope of variables in blocks is not supported. This means
variables declared inside a loop may be accessible outside of
the loop.
• There is a === operator, which tests not only for equality but
type equivalence.
Department of ISE
Identifiers or Name:
In javascript, identifiers, or names, are similar to those of other common
programming languages. They must begin with a letter, an underscore(_ ),
or a dollar sign($). Subsequent characters may be letters, underscore,
dollar signs or digits. There is no length limitation for identifiers.
Variable Name:
Variable name in javascript are case sensitive, meaning that SUM, Sum,
SuM, sum are all distinct names. However, by convention, programmer-
defined variable name do not include uppercase letters.
Department of ISE
Variables
• Variables in JavaScript are dynamically typed, meaning a
variable can be an integer, and then later a string, then later an
object.
• This simplifies variable declarations, so that we do not
require the familiar type fields like int, char, and String.
• To declare a variable x, we use the var keyword, the name,
and a semicolon
• If we specify no value, then (being typeless) the default value is
undefined.
Department of ISE
• Assignment can happen at declaration-time by appending the
value to the declaration, or at run time with a simple right-to-
left assignment
Department of ISE
Comments: Javascript has two forms of comments, both of which
are used in other languages.
1. //(two adjacent slashes)
2. /* to introduce the comment */.
Primitives, Operations, and Expressions
The primitive data types , operations and expressions of JavaScript are
similar to those of other common programming languages.
Primitive Types
JavaScript has five primitive types:
There are seven primitive data types:
1. string
2. number
3. bigint
4. boolean
5. undefined
6. symbol
7. null
Department of ISE
Operators
Department of ISE
Comparison Operators
Department of ISE
Logical Operators
• The Boolean operators AND (&&), OR(||), and NOT(!) and
their truth tables are listed below.
Department of ISE
The + Operator Used on Strings or The String Catenation operator
The + operator can also be used to add string variables or text values
together.
Numeric Operators
JavaScript has the typical collection of numeric operators. These
are The assignment operator = is used to assign values to
JavaScript variables. The arithmetic operator + is used to add
values together.
y=5; z=2; x=y+z;
Department of ISE
In programming, type conversion is the process of converting data
of one type to another. For example: converting String data to Number.
There are two types of type conversion in JavaScript.
•Implicit Conversion - automatic type conversion
•Explicit Conversion - manual type conversion
JavaScript Implicit Conversion
In certain situations, JavaScript automatically converts one data type to another (to the
right type). This is known as implicit conversion.
Department of ISE
Department of ISE
JavaScript Explicit Conversion
You can also convert one data type to another as per your needs. The type
conversion that you do manually is known as explicit type conversion.
In JavaScript, explicit type conversions are done using built-in methods.
Here are some common methods of explicit conversions.
Department of ISE
Department of ISE
Department of ISE
Department of ISE
String Properties and Methods
The String object includes one property, length, and a large collection of methods For
example Var str = “sudarsanan”; Var len = str.length;
Department of ISE
• Null and undefined are two distinctly different states for a
variable.
• Semicolons are not required, but are permitted (and
encouraged).
• There is no integer type, only number, which means floating-
point rounding errors are prevalent even with values intended
to be integers.
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"
typeof Operator
Department of ISE
• In addition, the conditional assignment operator can also be
used to assign a value based on condition.
Department of ISE
Difference Between Var and let
Department of ISE
Difference Between =, == and ===
Department of ISE
Arrays
An array is a special variable, which can hold more than one value.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
An array can hold many values under a single name, and you can access the values by
referring to an index number.
Using an array literal is the easiest way to create a JavaScript Array.
const array_name = [item1, item2, ...];
const cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
const cars = [
"Saab",
"Volvo",
"BMW"
];
Changing an Array Element
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Department of ISE
String Methods
• String length
• String slice()
• String substring()
• String substr()
• String replace()
• String replaceAll()
• String toUpperCase()
• String toLowerCase()
• String concat()
• String trim()
• String trimStart()
• String trimEnd()
• String padStart()
• String padEnd()
• String charAt()
• String charCodeAt()
• String split()
Department of ISE
String Length
The length property returns the length of a string:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Output: 26
String slice()
slice() extracts a part of a string and returns the extracted part
in a new string.
The method takes 2 parameters: start position, and end
position
Example
Slice out a portion of a string from position 7 to position 13:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
Output: Banana
String substring()
substring() is similar to slice().
The difference is that start and end values less than 0 are treated as 0 in
substring().
Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
Output: Banana
Department of ISE
String substr()
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
Output: Banana
If you omit the second parameter, substr() will slice out the rest of the string.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
Substring() vs Substr() vs Slice()
These methods are used to extract parts of a string and return the extracted parts in a new
string. All of these do not change the original string.
Department of ISE
Replacing String Content
The replace() method replaces a specified value with another value in a string:
Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
String.prototype.replaceAll()
The replaceAll() method returns a new string with all matches of a pattern replaced by a
replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a
function to be called for each match. The original string is left unchanged.
let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
Output: I love dogs. Dogs are very easy to love. Dogs are very popular.
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
JavaScript String concat()
Department of ISE
JavaScript String trim()
The trim() method removes whitespace from both sides of a string:
let text1 = " Hello World! ";
let text2 = text1.trim();
JavaScript String trimStart()
The trimStart() method works like trim(), but removes whitespace only from the start of a
string.
let text1 = " Hello World! ";
let text2 = text1.trimStart();
JavaScript String trimEnd()
The trimEnd() method works like trim(), but removes
whitespace only from the end of a string.
let text1 = " Hello World! ";
let text2 = text1.trimEnd();
Department of ISE
The padStart() method pads the current string with another string (multiple
times, if needed) until the resulting string reaches the given length. The
padding is applied from the start of the current string.
padStart()
let text = "5";
let padded = text.padStart(4,"x");
padEnd()
The padEnd() method pads the current string with a given string (repeated, if
needed) so that the resulting string reaches a given length. The padding is applied
from the end of the current string.
let text = "5";
let padded = text.padEnd(4,"x");
Department of ISE
JavaScript String charAt()
The charAt() method returns the character at a specified index (position) in a
string:
let text = "HELLO WORLD";
let char = text.charAt(0);
JavaScript String charCodeAt()
The charCodeAt() method returns the unicode of the character at a specified index in a
string:
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Department of ISE
JavaScript String split()
As the name implies, the split() method in JavaScript splits the string into the array of
substrings, puts these substrings into an array, and returns the new array. It does not
change the original string.
When the string is empty, rather than returning an empty array, the split() method
returns the array with an empty string. The empty array is returned when both string and
separator are empty strings.
Syntax
string.split(separator, limit)
var str = 'Welcome to the javaTpoint.com’
var arr = str.split("t");
document.write(arr);
Welcome,to,the
var str = 'Welcome to the javaTpoint.com’
var arr = str.split("t");
document.write(arr);
Welcome ,o ,he javaTpoin,.com
Department of ISE
Functions
• Functions are the building block for modular code in
JavaScript, and are even used to build pseudo-classes.
• Functions are defined by using the reserved word function and
then the function name and (optional) parameters.
• Since JavaScript is dynamically typed, functions do not require
a return type, nor do the parameters require type.
• Example
Department of ISE
Functions
Functions are one of the fundamental building blocks in JavaScript. A
function in JavaScript is similar to a procedure—a set of statements that
performs a task or calculates a value, but for a procedure to qualify as a
function, it should take some input and return an output
Function declarations
A function definition (also called a function declaration, or function statement)
consists of the function keyword, followed by:
•The name of the function.
•A list of parameters to the function, enclosed in parentheses and separated by
commas.
•The JavaScript statements that define the function, enclosed in curly brackets, { /* … */ }.
For example, the following code defines a simple function named square:
function square(number) { return number * number; }
function myFunc(theObject)
{
theObject.make = "Toyota";
}
const mycar = {
make: "Honda",
model: "Accord",
year: 1998,
};
// x gets the value "Honda"
const x = mycar.make;
// the make property is changed by the function
myFunc(mycar);
// y gets the value "Toyota"
const y = mycar.make;
Department of ISE
function myFunc(theArr) {
theArr[0] = 30;
}
const arr = [45];
console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30
const factorial = function fac(n)
{
return n < 2 ? 1 : n * fac(n - 1);
};
console.log(factorial(3));
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}
Department of ISE
Calling functions
Defining a function does not execute it. Defining it names the function and specifies what to
do when the function is called.
Calling the function actually performs the specified actions with the indicated parameters.
For example, if you define the function square, you could call it as follows:
square(5);
A function can call itself. For example, here is a function
that computes factorials recursively:
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
const a = factorial(1); // a gets the value 1
const b = factorial(2); // b gets the value 2
Department of ISE
Screen Output
JavaScript can "display" data in different ways:
• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
Department of ISE
Using innerHTML
To access an HTML element, JavaScript can use the
document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines
the HTML content:
Example:
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Department of ISE
Using document.write()
For testing purposes, it is convenient to use document.write():
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call document.write after the document has finished
loading.
It will overwrite the whole document.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Department of ISE
Using window.alert()
You can use an alert box to display data:
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Department of ISE
Alert
Window
alert("Welcome to
BMSCE");
Confirm
Window
registration=confirm(
"Do You want to register for 3rd
Sem ?");
Prompt
Window
name=prompt("Enter your
name:");
Department of ISE
Keyboard Input
The KeyboardEvent Object
The KeyboardEvent Object handles events that occur when a user
presses a key on the keyboard.
1. The keydown event is triggered first when user presses a key
2. The keyup event is triggered last when user releases a key
3. In between, the keypress event is triggered
Department of ISE
Keyboard Input
The KeyboardEvent Object
The KeyboardEvent Object handles events that occur when a user
presses a key on the keyboard.
i. onkeydown Event
The onkeydown event occurs when the user presses a key on the keyboard.
ii. onkeypress Event
The onkeypress event occurs when the user presses a key on the keyboard.
iii. onkeyup Event
The onkeyup event occurs when the user releases a key on the keyboard.
Department of ISE
Objects
In JavaScript, think of objects as a collection of ‘key:value’ pairs. This
brings to us the first and most popular way we create objects in
JavaScript.
1. Creating objects using object literal syntax
This is really simple. All you have to do is throw your key value pairs separated by ‘:’ inside a
set of curly braces({ }) and your object is ready to be served (or consumed), like below:
const person = { firstName: 'testFirstName', lastName: 'testLastName' };
2. Creating objects using the ‘new’ keyword
This method of object creation resembles the way objects are created in class-
based languages, like Java. By the way, starting with ES6, classes are native to
JavaScript as well and we will look at creating objects by defining classes towards
the end of this article. So, to create an object using the ‘new’ keyword, you need to
have a constructor function.
Department of ISE
Here are 2 ways you can use the ‘new’ keyword pattern —
a) Using the ‘new’ keyword with’ in-built Object constructor function
To create an object, use the new keyword with Object()constructor, like this:
const person = new Object();
Now, to add properties to this object, we have to do something like this:
person.firstName = 'testFirstName'; person.lastName = 'testLastName';
b) Using ‘new’ with user defined constructor function
The other problem with the approach of using the ‘Object’ constructor function result from the fact that
every time we create an object, we have to manually add the properties to the created object.
What if we had to create hundreds of person objects? You can imagine the pain now. So, to get rid of
manually adding properties to the objects, we create custom (or user-defined) functions. We first create a
constructor function and then use the ‘new’ keyword to get objects:
function Person(fname, lname)
{
this.firstName = fname;
this.lastName = lname;
}
Now, anytime you want a ‘Person’ object, just do this:
const personOne = new Person('testFirstNameOne', 'testLastNameOne’);
const personTwo = new Person('testFirstNameTwo', 'testLastNameTwo');
Department of ISE
Conditionals (If, else if, …, else)
• JavaScript’s syntax is almost identical to that of PHP, Java, or
C when it comes to conditional structures such as if and if else
statements.
• In this syntax the condition to test is contained within ( )
brackets with the body contained in { } blocks.
• Example – Conditional statement setting a variable based on
the hour of the day.
Department of ISE
Department of ISE
Loops
• Like conditionals, loops use the ( ) and { } blocks to define the
condition and the body of the loop.
While Loop
• The most basic loop is the while loop, which loops until the
condition is true.
• While loop initialize a loop control variable before the loop,
use it in the condition, and modify it within the loop.
var i=0; // initialise the Loop Control Variable
while(i < 10){ //test the loop control variable
i++; //increment the loop control variable
}
Department of ISE
For Loops
• A for loop combines the common components of a loop:
initialization, condition, and post-loop operation into one
statement. This statement begins with the for keyword and has
the components placed between ( ) brackets, semicolon (;)
separated.
Department of ISE
Errors Using Try and Catch
• When the browser’s JavaScript engine encounters an error, it
will throw an exception.
• These exceptions interrupt the regular, sequential execution
of the program and can stop the JavaScript engine altogether.
• However, you can optionally catch these errors preventing
disruption of the program using the try–catch block.
Department of ISE
Throwing Your Own Exceptions
• try-catch can be used exclusively to catch built-in JavaScript
errors, it can also be used by your programs, to throw your own
messages.
• The throw keyword stops normal sequential execution.
• try-catch and throw statements should be used for abnormal
or exceptional cases in your program.
Throwing a user-defined exception
Department of ISE
JavaScript Objects
• JavaScript is not a full-fledged object-oriented programming
language, so it does not support many object-oriented language
concepts like inheritance and polymorphism.
• The language however, support objects.
• Objects can have constructors, properties, and methods
associated with them, and are used objects like in any other
object-oriented languages.
• There are objects that are included in the JavaScript language;
you can also define your own kind of objects.
Department of ISE
Constructors
• To create a new object we use the new keyword, the class
name, and ( ) brackets with n optional parameters inside,
comma delimited as follows.
var someObject = new ObjectName(parameter 1,param
2,..., parameter n);
• For some classes, shortcut constructors are defined.
var greeting = "Good Morning";
• Instead of the formal definition
var greeting = new String("Good Morning");
Department of ISE
Properties
• Each object might have properties that can be accessed,
depending on its definition.
• When a property exists, it can be accessed using dot notation
where a dot between the instance name and the property
references that property.
alert(someObject.property); //show someObject.property to
the user
Department of ISE
Methods
• Objects can also have methods, which are functions associated
with an instance of an object.
• These methods are called using the same dot notation as for
properties, but instead of accessing a variable, we are calling a
method.
someObject.doSomething();
• Methods may produce different output depending on the object
they are associated with because they can utilize the internal
properties of the object.
Department of ISE
Objects Included in JavaScript
• A number of useful objects are included in JavaScript. They are
Array, Boolean, Date, Math, String, and others.
• In addition to these, JavaScript can also access Document
Object Model (DOM) objects that correspond to the content
of a HTML pages.
• These DOM objects let JavaScript code access and modify
HTML and CSS properties of a page dynamically.
Department of ISE
Arrays
• The following code creates a new, empty array named
greetings:
var greetings = new Array();
• To initialize the array with values, the variable declaration
would look like the following:
var greetings = new Array("Good Morning", "Good
Afternoon");
• or, using the square bracket notation:
var greetings = ["Good Morning", "Good Afternoon"];
Department of ISE
Accessing and Traversing an Array
• To access an element in the array, use square bracket notation
from Java and C - languages, with the index you wish to access
inside the brackets.
alert ( greetings[0] );
• One of the most common actions on an array is to traverse
through the items sequentially.
• The following for loop quickly loops through an array,
accessing the ith element each time using the Array object’s
length property to determine the maximum valid index. It will
alert “Good Morning” and “Good Afternoon” to the user.
Department of ISE
for (var i = 0; i < greetings.length; i++)
{
alert(greetings[i]);
}
Department of ISE
Modifying an Array
• To add an item to an existing array, you can use the push method.
greetings.push("Good Evening");
• The pop method can be used to remove an item from the back of
an array.
• Other methods are used to modify arrays include concat(), slice(),
join(), reverse(), shift(), and sort().
Department of ISE
Math
• The Math class allows one to access common mathematic
functions and common values quickly in one place.
• This static class contains methods such as max(), min(), pow(),
sqrt(), and exp(), and trigonometric functions such as sin(), cos(),
andarctan().
• In addition, many mathematical constants are defined such as PI,
E (Euler’s number), SQRT2 etc..
Department of ISE
String
• To create a String object.
• To get the length of a string, the length property is used.
alert (greet.length); // will display "4“
• Another usage of strings is to concatenate them together, the +
operator has been overridden to allow for concatenation.
Department of ISE
• Many other useful methods exist within the String class, such as
accessing a single character using charAt(), or searching for one
using indexOf().
• Strings allow splitting a string into an array, searching and
matching with split(), search(), and match() methods.
Department of ISE
Date
• It is used to calculate the current date or create date objects for
particular dates.
• To display today’s date as a string, simply create a new object and
use the toString() method.
Department of ISE
Window Object
• The window object in JavaScript corresponds to the browser
itself.
• Through it, you can access the current page’s URL, the browser’s
history, and what’s being displayed in the status bar, as well as
opening new browser windows.
• the alert() function is actually a method of the window object.
Department of ISE
The Document Object Model (DOM)
• JavaScript is used to interact with the HTML document in which
it is contained.
• This is accomplished through a programming interface (API)
called the Document Object Model.
• According to the W3C, the DOM is a:
Platform- and language-neutral interface that will allow
programs and scripts to dynamically access and update the
content, structure and style of documents.
Department of ISE
DOM
Tree
Department of ISE
Department of ISE
DOM Nodes
• In DOM Tree the root or topmost object is called the Document
Root.
• Each element within the HTML document is called a node. If the
DOM is a tree, then each node is an individual branch.
• There are:
1) Element nodes,
2) Text nodes,
3) Attribute nodes
Department of ISE
Department of ISE
• All nodes in the DOM share a common set of properties and
methods.
• Thus, most typical task perform in JavaScript involve finding a
node, and then accessing or modifying it via properties and
methods.
• The most important properties are shown in below table.
Department of ISE
Some Essential Node Object Properties
Department of ISE
Document Object
• The DOM document object is the root JavaScript object
representing the entire HTML document.
• It contains some properties and methods that we will use
extensively in development and is globally accessible as
document.
• Accessing the properties is done through the dot notation.
Department of ISE
Some Essential Document Object Methods
Department of ISE
Accessing nodes
Relationship between HTML tags and getElementByID() and
getElementsByTagName()
Department of ISE
Element node Object
• IDs must be unique in an HTML document,getElementByID()
returns a single node.
Some Essential Element Node Properties
Department of ISE
Modifying a DOM Element
• document.write() method is used to create output to the HTML
page from JavaScript. It always creates JavaScript at the bottom
of the existing HTML page
.
• The modern JavaScript programmer will want to write to the
HTML page, but in a particular location, not always at the
bottom.
• By using DOM document and HTML DOM element objects,
we can do exactly that using the innerHTML property.
Department of ISE
Changing the HTML using innerHTML
Out put :
Department of ISE
Changing an element’s style
• We can add or remove any style using the style or className
property of the Element node.
• The className property is normally a better choice, because it
allows the styles to be created outside the code, and thus be better
accessible to designers.
var commentTag = document.getElementById("specificTag");
commentTag.className = "someClassName";
Department of ISE
• HTML5 introduces the classList element, which allows you to
add, remove, or toggle a CSS class on an element.
label.classList.addClass("someClassName");
Department of ISE
Additional Properties
Department of ISE
Example to get the password out of the following input field.
Department of ISE
JavaScript Events
• A JavaScript event is an action that can be detected by
JavaScript.
• Many of them are initiated by user actions but some are
generated by the browser itself.
• When an event is triggered, it will catch by JavaScript functions,
which then do something in response.
• In the original mechanism Events could be specified right in the
HTML markup with hooks to the JavaScript code.
• As more powerful frameworks were developed this original
mechanism was supplanted by the listener approach.
Department of ISE
• Note : Old method uses the JavaScript right inside the HTML,
while the listener technique has removed JavaScript from the
markup, resulting in cleaner, easier to maintain HTML code.
Department of ISE
• Inline hooks versus the Layered Listener technique
Department of ISE
Inline Event Handler Approach
• Using JavaScript within HTML makes inline.
• For example, if you wanted an alert to pop-up when clicking a
<div>.
• In above example the HTML attribute onclick is used to attach a
handler to event. When the user clicks the <div>, the event is
triggered and the alert is executed.
• The problem with this type of programming is that the HTML
markup and the corresponding JavaScript logic are woven
together. It does not make use of layers;
• It does not separate content from behaviour.
Department of ISE
Listener Approach
• The design principle of layers proved that it increases
maintainability and simplifies markup.
• The problem with the inline handler approach is that it does not
make use of layers; that is, it does not separate content from
behavior.
• Listener approach separates all JavaScript code from the HTML
markup.
Department of ISE
• There are two ways you can use listener approach
i). The “old” style of registering a listener
<div id="example1"></div>
ii). The “new” DOM2 approach to registering listeners.
Department of ISE
• The one limitation with the inline approach is that only one
handler can respond to any given element event.
• By using addEventListener() shown in the above example,
multiple handlers can be assigned to a single object’s event.
Listening to an event with a function
Department of ISE
Event Types
• There are several classes of event, with different types of event
within each class specified by the W3C.
• The classes are
1. Mouse events
2. Keyboard events
3. Form events
4. Frame events.
i). Mouse events
• Mouse events are defined to capture a range of interactions driven
by the mouse.
• These can be further categorized as mouse click and mouse move
events.
Department of ISE
Mouse Events in JavaScript
ii). Keyboard Events
Department of ISE
ii). Keyboard Events
<input type="text"
id="keyExample">
•The input box above, could be listened to and each key pressed echoed
back to the user as an alert.
Department of ISE
Keyboard Events in JavaScript
Department of ISE
iii). Form Events
• Through Forms user input is collected and transmitted to the
server.
• The events triggered by forms allow us to do some timely
processing in response to user input.
• The most common JavaScript listener for forms is the onsubmit
event.
Department of ISE
• In the below example we listen for that event on a form with id
loginForm.
• If the password field (with id pw) is blank, we prevent submitting
to the server using preventDefault() and alert the user.
Exmaple Catching the onsubmit event and validating a password to not
be blank
Department of ISE
Form Events in JavaScript
Department of ISE
iv). Frame Events
• Frame events are the events related to the browser frame that
contains your web page.
• The most important event is the onload event, which tells us an
object is loaded and therefore ready to work with.
• However, a problem can occur if the JavaScript tries to reference
a particular <div> in the HTML page that has not yet been loaded.
• If the code attempts to set up a listener on this not-yet-loaded
<div>, then an error will be triggered. For this reason it is
common practice to use the window.onload event to trigger the
execution of the rest of the page’s scripts.
Department of ISE
• The above code will only run once the page is fully loaded and
therefore all references to the page’s HTML elements will be
valid.
Department of ISE
Frame Events in JavaScript
Department of ISE
Forms
• Consider a basic HTML form for a login example
Department of ISE
Validating Forms
• User form input should be validated on both the client side and the
server side.
• Form validation is one of the most common applications of
JavaScript.
• Writing code to prevalidate forms on the client side will reduce
the number of incorrect submissions, thereby reducing server load.
• There are a number of common validation activities including
email validation, number validation, and data validation.
Department of ISE
Empty Field Validation
• A common application of a client-side validation is to make sure
the user entered something into a field.
• To check for an empty field in JavaScript is to compare a value to
both null and the empty string ("") to ensure it is not empty.
Department of ISE
Number Validation
Submitting Forms
• Submitting a form using JavaScript requires having a variable for
the form element.
• Once the variable, say, formExample is acquired, one can simply
call the submit() method:
• This is often done in conjunction with calling preventDefault()
on the onsubmit event.

More Related Content

Similar to WTA-MODULE-4.pptx

Similar to WTA-MODULE-4.pptx (20)

Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
Java Script - A New Look
Java Script - A New LookJava Script - A New Look
Java Script - A New Look
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
Iwt note(module 2)
Iwt note(module 2)Iwt note(module 2)
Iwt note(module 2)
 
Java script
Java scriptJava script
Java script
 
JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTING
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Welcome to React.pptx
Welcome to React.pptxWelcome to React.pptx
Welcome to React.pptx
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
 
js.pptx
js.pptxjs.pptx
js.pptx
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
 
Java script.pptx v
Java script.pptx                                     vJava script.pptx                                     v
Java script.pptx v
 
Javascript
JavascriptJavascript
Javascript
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Servlets and jsp pages best practices
Servlets and jsp pages best practicesServlets and jsp pages best practices
Servlets and jsp pages best practices
 
Java script
Java scriptJava script
Java script
 
Introduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and ToolsIntroduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and Tools
 

Recently uploaded

UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Recently uploaded (20)

UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 

WTA-MODULE-4.pptx

  • 1. Department of ISE WEB TECHNOLOGY Unit 4 Basics of JavaScript Dr. CHAYAPATHI A R Assistant Professor BMSCE, Bangalore
  • 2. Department of ISE Module 3: Overview of JavaScript, The <script> tag, Document Object Model (DOM) General Syntactic Characteristics, Primitives, variables, usage of let and var, typeof operator, Operations, expressions, == and === operator differences, Screen output and keyboard input, Control statements, Arrays, strings, string methods, Objects, Regular Expressions, functions.
  • 3. Department of ISE What is JavaScript and What can it do? • JavaScript is an object-oriented, dynamically typed, client- side scripting language. • Although it contains the word Java, JavaScript and Java are vastly different programming languages with different uses. • Java is a full-fledged compiled, object oriented language, popular for its ability to run on any platform with a Java Virtual Machine installed. • Where as JavaScript is one of the world’s most popular languages, with fewer of the object-oriented features of Java, and runs directly inside the browser, without the need for the JVM.
  • 4. Department of ISE • JavaScript was introduced by Netscape in their Navigator browser back in 1996. • It was originally called LiveScript. • JavaScript is in fact an implementation of a standardized scripting language called ECMAScript. • Internet Explorer (IE) at first did not support JavaScript, but instead had its own browser-based scripting language (VBScript). While IE now does support JavaScript. • Microsoft sometimes refers to it as JScript, primarily for trademark reasons (Oracle currently owns the trademark for JavaScript).
  • 5. Department of ISE • JavaScript is dynamically typed (also called weakly typed) in that variables can be easily (or implicitly) converted from one data type to another. • The type of data a variable can hold is assigned at runtime and can change during run time as well. JavaScript can be divided into three parts: The core javascript Client side javascript Server side javascrip The core is the heart of the language, including its operators, expressions, statements and subprograms. Client side JavaScript is a collection of objects that support control of a browser and interaction with users For example With JavaScript, an XHTML document can be made to be responsive to user inputs such as mouse clicks and keyboard use. Server-side JavaScript is a collection of objects that make the language useful on a Web Server; For example:To support communication with a database management system.
  • 6. Department of ISE Client-Side Scripting - It refers to the client machine (i.e., the browser) running code locally rather than relying on the server to execute code and return the result. Downloading and executing a client-side JavaScript script
  • 7. Department of ISE • Advantages of client-side scripting 1. Processing can be offloaded from the server to client machines, thereby reducing the load on the server. 2. The browser can respond more rapidly to user events than a request to a remote server ever could, which improves the user experience. 3. JavaScript can interact with the downloaded HTML in a way that the server cannot, creating a user experience more like desktop software.
  • 8. Department of ISE • Disadvantages of client-side scripting 1. There is no guarantee that the client has JavaScript enabled 2. The idiosyncrasies between various browsers and operating systems make it difficult to test for all potential client configurations. What works in one browser, may generate an error in another. 3. JavaScript-heavy web applications can be complicated to debug and maintain.
  • 9. Department of ISE JavaScript in Modern Times (AJAX) • Earlier (in 1998) JavaScript was only slightly useful, and quite often, had only a few common uses: graphic roll-overs (that is, swapping one image for another when the user hovered the mouse over an image), pop-up alert messages, scrolling text in the status bar, opening new browser windows, and prevalidating user data in online forms. • JavaScript became a much more important part of web development in the mid 2000s with AJAX. • AJAX : means Asynchronous JavaScript And XML.
  • 10. Department of ISE • AJAX refers to a style of website development that makes use of JavaScript to create more responsive user experience and also it helps to create asynchronous web applications. • The most important feature of AJAX sites is the asynchronous data requests. (not blocking client or browser)
  • 11. Department of ISE JavaScript and Java JavaScript is not an object-oriented programming language. Rather, it is an object- based language. JavaScript does not have classes. Its objects serve both as objects and as models of objects. JavaScript it support class-based inheritance, like a technique called prototype object, thus , this form of inheritance is called prototype- based inheritance.
  • 12. Department of ISE JavaScript Objects: In JavaScript, objects are collections of properties (Properties are the values associated with an object), Which corresponds to the members of classes in Java and C++. For example: In the following example we are using the length property of the String object to return the number of characters in a string var txt="Hello World!"; document.write(txt.length); Each property is either a data property or a function or method property. Data properties appear in two categories: primitive values and references to other objects. ( In JavaScript, variables that refer to objects are often called objects rather than references.) Methods Methods are the actions that can be performed on objects. In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters: <script type="text/javascript"> var str="Hello world!"; document.write(str.toUpperCase()); </script>
  • 13. Department of ISE General Syntactic Characteristics JavaScript scripts will be embedded in HTML documents •Either directly, as in <script type = "text/javaScript"> -- JavaScript script - </script> •Or indirectly, as a file specified in the src attribute of <script>, as in <script type = "text/javaScript“ src = "myScript.js"> </script>
  • 14. Department of ISE Where Does JavaScript Go? • JavaScript can be linked to an HTML page in a number of ways. 1. Inline 2. Embedded 3. External • Among these 3 methods external is the preferred method for cleanliness and ease of maintenance. • Running JavaScript scripts in browser requires downloading the JavaScript code to the browser and then running it.
  • 15. Department of ISE • Pages with lots of scripts could potentially run slowly, resulting in a degraded experience while users wait for the page to load. • Different browsers manage the downloading and loading of scripts in different ways.
  • 16. Department of ISE Inline JavaScript • Inline JavaScript refers to including JavaScript code directly within certain HTML attributes. • Inline method in general a bad practice and should be avoided. • In fact, inline JavaScript is much worse than inline CSS. • Inline JavaScript is a real maintenance nightmare, requiring to scan through almost every line of HTML looking for your inline JavaScript.
  • 17. Department of ISE Embedded JavaScript • Embedded JavaScript refers to the placing JavaScript code within a <script> Element. • Embedded JavaScript can be used for quick testing and for learning scenarios, but it is also difficult to maintain like inline method.
  • 18. Department of ISE External JavaScript • It is advantageous to separate the HTML and JavaScript into two different files. • JavaScript supports this separation by allowing links to an external file that contains the JavaScript. • This is the recommended way of including JavaScript scripts in your HTML pages.
  • 19. Department of ISE • JavaScript external files have the extension .js • The link to the external JavaScript file can be placed within the <head> element, or within the <body> element. • The advantage of placing external scripts at the bottom of the <body> can increase the performance. • A JavaScript file has to be loaded completely before the browser can begin any other downloads, For sites with multiple external JavaScript files, this can cause delay in initial page rendering.
  • 20. Department of ISE • Similarly, if the page is loading a third-party JavaScript library from an external site, and that site becomes unavailable or especially slow, then your pages will be rendered especially slow.
  • 21. Department of ISE JavaScript Syntax • Most common programming constructs including variables, assignment, conditionals, loops, and arrays before moving on to advanced topics such as events and classes. JavaScript’s features. • Everything is type sensitive, including function, class, and variable names. • The scope of variables in blocks is not supported. This means variables declared inside a loop may be accessible outside of the loop. • There is a === operator, which tests not only for equality but type equivalence.
  • 22. Department of ISE Identifiers or Name: In javascript, identifiers, or names, are similar to those of other common programming languages. They must begin with a letter, an underscore(_ ), or a dollar sign($). Subsequent characters may be letters, underscore, dollar signs or digits. There is no length limitation for identifiers. Variable Name: Variable name in javascript are case sensitive, meaning that SUM, Sum, SuM, sum are all distinct names. However, by convention, programmer- defined variable name do not include uppercase letters.
  • 23. Department of ISE Variables • Variables in JavaScript are dynamically typed, meaning a variable can be an integer, and then later a string, then later an object. • This simplifies variable declarations, so that we do not require the familiar type fields like int, char, and String. • To declare a variable x, we use the var keyword, the name, and a semicolon • If we specify no value, then (being typeless) the default value is undefined.
  • 24. Department of ISE • Assignment can happen at declaration-time by appending the value to the declaration, or at run time with a simple right-to- left assignment
  • 25. Department of ISE Comments: Javascript has two forms of comments, both of which are used in other languages. 1. //(two adjacent slashes) 2. /* to introduce the comment */. Primitives, Operations, and Expressions The primitive data types , operations and expressions of JavaScript are similar to those of other common programming languages. Primitive Types JavaScript has five primitive types: There are seven primitive data types: 1. string 2. number 3. bigint 4. boolean 5. undefined 6. symbol 7. null
  • 28. Department of ISE Logical Operators • The Boolean operators AND (&&), OR(||), and NOT(!) and their truth tables are listed below.
  • 29. Department of ISE The + Operator Used on Strings or The String Catenation operator The + operator can also be used to add string variables or text values together. Numeric Operators JavaScript has the typical collection of numeric operators. These are The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together. y=5; z=2; x=y+z;
  • 30. Department of ISE In programming, type conversion is the process of converting data of one type to another. For example: converting String data to Number. There are two types of type conversion in JavaScript. •Implicit Conversion - automatic type conversion •Explicit Conversion - manual type conversion JavaScript Implicit Conversion In certain situations, JavaScript automatically converts one data type to another (to the right type). This is known as implicit conversion.
  • 32. Department of ISE JavaScript Explicit Conversion You can also convert one data type to another as per your needs. The type conversion that you do manually is known as explicit type conversion. In JavaScript, explicit type conversions are done using built-in methods. Here are some common methods of explicit conversions.
  • 36. Department of ISE String Properties and Methods The String object includes one property, length, and a large collection of methods For example Var str = “sudarsanan”; Var len = str.length;
  • 37. Department of ISE • Null and undefined are two distinctly different states for a variable. • Semicolons are not required, but are permitted (and encouraged). • There is no integer type, only number, which means floating- point rounding errors are prevalent even with values intended to be integers. typeof "John" // Returns "string" typeof 3.14 // Returns "number" typeof NaN // Returns "number" typeof false // Returns "boolean" typeof [1,2,3,4] // Returns "object" typeof {name:'John', age:34} // Returns "object" typeof new Date() // Returns "object" typeof function () {} // Returns "function" typeof myCar // Returns "undefined" * typeof null // Returns "object" typeof Operator
  • 38. Department of ISE • In addition, the conditional assignment operator can also be used to assign a value based on condition.
  • 39. Department of ISE Difference Between Var and let
  • 40. Department of ISE Difference Between =, == and ===
  • 41. Department of ISE Arrays An array is a special variable, which can hold more than one value. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: let car1 = "Saab"; let car2 = "Volvo"; let car3 = "BMW"; An array can hold many values under a single name, and you can access the values by referring to an index number. Using an array literal is the easiest way to create a JavaScript Array. const array_name = [item1, item2, ...]; const cars = ["Saab", "Volvo", "BMW"]; Spaces and line breaks are not important. A declaration can span multiple lines: const cars = [ "Saab", "Volvo", "BMW" ]; Changing an Array Element Example const cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Opel";
  • 42. Department of ISE String Methods • String length • String slice() • String substring() • String substr() • String replace() • String replaceAll() • String toUpperCase() • String toLowerCase() • String concat() • String trim() • String trimStart() • String trimEnd() • String padStart() • String padEnd() • String charAt() • String charCodeAt() • String split()
  • 43. Department of ISE String Length The length property returns the length of a string: let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let length = text.length; Output: 26 String slice() slice() extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: start position, and end position Example Slice out a portion of a string from position 7 to position 13: let text = "Apple, Banana, Kiwi"; let part = text.slice(7, 13); Output: Banana String substring() substring() is similar to slice(). The difference is that start and end values less than 0 are treated as 0 in substring(). Example let str = "Apple, Banana, Kiwi"; let part = str.substring(7, 13); Output: Banana
  • 44. Department of ISE String substr() substr() is similar to slice(). The difference is that the second parameter specifies the length of the extracted part. Example let str = "Apple, Banana, Kiwi"; let part = str.substr(7, 6); Output: Banana If you omit the second parameter, substr() will slice out the rest of the string. let str = "Apple, Banana, Kiwi"; let part = str.substr(7); Substring() vs Substr() vs Slice() These methods are used to extract parts of a string and return the extracted parts in a new string. All of these do not change the original string.
  • 45. Department of ISE Replacing String Content The replace() method replaces a specified value with another value in a string: Example let text = "Please visit Microsoft!"; let newText = text.replace("Microsoft", "W3Schools"); String.prototype.replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged. let text = "I love cats. Cats are very easy to love. Cats are very popular." text = text.replaceAll("Cats","Dogs"); Output: I love dogs. Dogs are very easy to love. Dogs are very popular. let text1 = "Hello"; let text2 = "World"; let text3 = text1.concat(" ", text2); JavaScript String concat()
  • 46. Department of ISE JavaScript String trim() The trim() method removes whitespace from both sides of a string: let text1 = " Hello World! "; let text2 = text1.trim(); JavaScript String trimStart() The trimStart() method works like trim(), but removes whitespace only from the start of a string. let text1 = " Hello World! "; let text2 = text1.trimStart(); JavaScript String trimEnd() The trimEnd() method works like trim(), but removes whitespace only from the end of a string. let text1 = " Hello World! "; let text2 = text1.trimEnd();
  • 47. Department of ISE The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string. padStart() let text = "5"; let padded = text.padStart(4,"x"); padEnd() The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end of the current string. let text = "5"; let padded = text.padEnd(4,"x");
  • 48. Department of ISE JavaScript String charAt() The charAt() method returns the character at a specified index (position) in a string: let text = "HELLO WORLD"; let char = text.charAt(0); JavaScript String charCodeAt() The charCodeAt() method returns the unicode of the character at a specified index in a string: let text = "HELLO WORLD"; let char = text.charCodeAt(0);
  • 49. Department of ISE JavaScript String split() As the name implies, the split() method in JavaScript splits the string into the array of substrings, puts these substrings into an array, and returns the new array. It does not change the original string. When the string is empty, rather than returning an empty array, the split() method returns the array with an empty string. The empty array is returned when both string and separator are empty strings. Syntax string.split(separator, limit) var str = 'Welcome to the javaTpoint.com’ var arr = str.split("t"); document.write(arr); Welcome,to,the var str = 'Welcome to the javaTpoint.com’ var arr = str.split("t"); document.write(arr); Welcome ,o ,he javaTpoin,.com
  • 50. Department of ISE Functions • Functions are the building block for modular code in JavaScript, and are even used to build pseudo-classes. • Functions are defined by using the reserved word function and then the function name and (optional) parameters. • Since JavaScript is dynamically typed, functions do not require a return type, nor do the parameters require type. • Example
  • 51. Department of ISE Functions Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output Function declarations A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: •The name of the function. •A list of parameters to the function, enclosed in parentheses and separated by commas. •The JavaScript statements that define the function, enclosed in curly brackets, { /* … */ }. For example, the following code defines a simple function named square: function square(number) { return number * number; } function myFunc(theObject) { theObject.make = "Toyota"; } const mycar = { make: "Honda", model: "Accord", year: 1998, }; // x gets the value "Honda" const x = mycar.make; // the make property is changed by the function myFunc(mycar); // y gets the value "Toyota" const y = mycar.make;
  • 52. Department of ISE function myFunc(theArr) { theArr[0] = 30; } const arr = [45]; console.log(arr[0]); // 45 myFunc(arr); console.log(arr[0]); // 30 const factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); }; console.log(factorial(3)); function map(f, a) { const result = new Array(a.length); for (let i = 0; i < a.length; i++) { result[i] = f(a[i]); } return result; }
  • 53. Department of ISE Calling functions Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows: square(5); A function can call itself. For example, here is a function that computes factorials recursively: function factorial(n) { if (n === 0 || n === 1) { return 1; } else { return n * factorial(n - 1); } } const a = factorial(1); // a gets the value 1 const b = factorial(2); // b gets the value 2
  • 54. Department of ISE Screen Output JavaScript can "display" data in different ways: • Writing into an HTML element, using innerHTML. • Writing into the HTML output using document.write(). • Writing into an alert box, using window.alert(). • Writing into the browser console, using console.log().
  • 55. Department of ISE Using innerHTML To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content: Example: <html> <body> <h2>My First Web Page</h2> <p>My First Paragraph.</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = 5 + 6; </script> </body> </html>
  • 56. Department of ISE Using document.write() For testing purposes, it is convenient to use document.write(): <html> <body> <h2>My First Web Page</h2> <p>My first paragraph.</p> <p>Never call document.write after the document has finished loading. It will overwrite the whole document.</p> <script> document.write(5 + 6); </script> </body> </html>
  • 57. Department of ISE Using window.alert() You can use an alert box to display data: <html> <body> <h2>My First Web Page</h2> <p>My first paragraph.</p> <script> window.alert(5 + 6); </script> </body> </html>
  • 58. Department of ISE Alert Window alert("Welcome to BMSCE"); Confirm Window registration=confirm( "Do You want to register for 3rd Sem ?"); Prompt Window name=prompt("Enter your name:");
  • 59. Department of ISE Keyboard Input The KeyboardEvent Object The KeyboardEvent Object handles events that occur when a user presses a key on the keyboard. 1. The keydown event is triggered first when user presses a key 2. The keyup event is triggered last when user releases a key 3. In between, the keypress event is triggered
  • 60. Department of ISE Keyboard Input The KeyboardEvent Object The KeyboardEvent Object handles events that occur when a user presses a key on the keyboard. i. onkeydown Event The onkeydown event occurs when the user presses a key on the keyboard. ii. onkeypress Event The onkeypress event occurs when the user presses a key on the keyboard. iii. onkeyup Event The onkeyup event occurs when the user releases a key on the keyboard.
  • 61. Department of ISE Objects In JavaScript, think of objects as a collection of ‘key:value’ pairs. This brings to us the first and most popular way we create objects in JavaScript. 1. Creating objects using object literal syntax This is really simple. All you have to do is throw your key value pairs separated by ‘:’ inside a set of curly braces({ }) and your object is ready to be served (or consumed), like below: const person = { firstName: 'testFirstName', lastName: 'testLastName' }; 2. Creating objects using the ‘new’ keyword This method of object creation resembles the way objects are created in class- based languages, like Java. By the way, starting with ES6, classes are native to JavaScript as well and we will look at creating objects by defining classes towards the end of this article. So, to create an object using the ‘new’ keyword, you need to have a constructor function.
  • 62. Department of ISE Here are 2 ways you can use the ‘new’ keyword pattern — a) Using the ‘new’ keyword with’ in-built Object constructor function To create an object, use the new keyword with Object()constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.firstName = 'testFirstName'; person.lastName = 'testLastName'; b) Using ‘new’ with user defined constructor function The other problem with the approach of using the ‘Object’ constructor function result from the fact that every time we create an object, we have to manually add the properties to the created object. What if we had to create hundreds of person objects? You can imagine the pain now. So, to get rid of manually adding properties to the objects, we create custom (or user-defined) functions. We first create a constructor function and then use the ‘new’ keyword to get objects: function Person(fname, lname) { this.firstName = fname; this.lastName = lname; } Now, anytime you want a ‘Person’ object, just do this: const personOne = new Person('testFirstNameOne', 'testLastNameOne’); const personTwo = new Person('testFirstNameTwo', 'testLastNameTwo');
  • 63. Department of ISE Conditionals (If, else if, …, else) • JavaScript’s syntax is almost identical to that of PHP, Java, or C when it comes to conditional structures such as if and if else statements. • In this syntax the condition to test is contained within ( ) brackets with the body contained in { } blocks. • Example – Conditional statement setting a variable based on the hour of the day.
  • 65. Department of ISE Loops • Like conditionals, loops use the ( ) and { } blocks to define the condition and the body of the loop. While Loop • The most basic loop is the while loop, which loops until the condition is true. • While loop initialize a loop control variable before the loop, use it in the condition, and modify it within the loop. var i=0; // initialise the Loop Control Variable while(i < 10){ //test the loop control variable i++; //increment the loop control variable }
  • 66. Department of ISE For Loops • A for loop combines the common components of a loop: initialization, condition, and post-loop operation into one statement. This statement begins with the for keyword and has the components placed between ( ) brackets, semicolon (;) separated.
  • 67. Department of ISE Errors Using Try and Catch • When the browser’s JavaScript engine encounters an error, it will throw an exception. • These exceptions interrupt the regular, sequential execution of the program and can stop the JavaScript engine altogether. • However, you can optionally catch these errors preventing disruption of the program using the try–catch block.
  • 68. Department of ISE Throwing Your Own Exceptions • try-catch can be used exclusively to catch built-in JavaScript errors, it can also be used by your programs, to throw your own messages. • The throw keyword stops normal sequential execution. • try-catch and throw statements should be used for abnormal or exceptional cases in your program. Throwing a user-defined exception
  • 69. Department of ISE JavaScript Objects • JavaScript is not a full-fledged object-oriented programming language, so it does not support many object-oriented language concepts like inheritance and polymorphism. • The language however, support objects. • Objects can have constructors, properties, and methods associated with them, and are used objects like in any other object-oriented languages. • There are objects that are included in the JavaScript language; you can also define your own kind of objects.
  • 70. Department of ISE Constructors • To create a new object we use the new keyword, the class name, and ( ) brackets with n optional parameters inside, comma delimited as follows. var someObject = new ObjectName(parameter 1,param 2,..., parameter n); • For some classes, shortcut constructors are defined. var greeting = "Good Morning"; • Instead of the formal definition var greeting = new String("Good Morning");
  • 71. Department of ISE Properties • Each object might have properties that can be accessed, depending on its definition. • When a property exists, it can be accessed using dot notation where a dot between the instance name and the property references that property. alert(someObject.property); //show someObject.property to the user
  • 72. Department of ISE Methods • Objects can also have methods, which are functions associated with an instance of an object. • These methods are called using the same dot notation as for properties, but instead of accessing a variable, we are calling a method. someObject.doSomething(); • Methods may produce different output depending on the object they are associated with because they can utilize the internal properties of the object.
  • 73. Department of ISE Objects Included in JavaScript • A number of useful objects are included in JavaScript. They are Array, Boolean, Date, Math, String, and others. • In addition to these, JavaScript can also access Document Object Model (DOM) objects that correspond to the content of a HTML pages. • These DOM objects let JavaScript code access and modify HTML and CSS properties of a page dynamically.
  • 74. Department of ISE Arrays • The following code creates a new, empty array named greetings: var greetings = new Array(); • To initialize the array with values, the variable declaration would look like the following: var greetings = new Array("Good Morning", "Good Afternoon"); • or, using the square bracket notation: var greetings = ["Good Morning", "Good Afternoon"];
  • 75. Department of ISE Accessing and Traversing an Array • To access an element in the array, use square bracket notation from Java and C - languages, with the index you wish to access inside the brackets. alert ( greetings[0] ); • One of the most common actions on an array is to traverse through the items sequentially. • The following for loop quickly loops through an array, accessing the ith element each time using the Array object’s length property to determine the maximum valid index. It will alert “Good Morning” and “Good Afternoon” to the user.
  • 76. Department of ISE for (var i = 0; i < greetings.length; i++) { alert(greetings[i]); }
  • 77. Department of ISE Modifying an Array • To add an item to an existing array, you can use the push method. greetings.push("Good Evening"); • The pop method can be used to remove an item from the back of an array. • Other methods are used to modify arrays include concat(), slice(), join(), reverse(), shift(), and sort().
  • 78. Department of ISE Math • The Math class allows one to access common mathematic functions and common values quickly in one place. • This static class contains methods such as max(), min(), pow(), sqrt(), and exp(), and trigonometric functions such as sin(), cos(), andarctan(). • In addition, many mathematical constants are defined such as PI, E (Euler’s number), SQRT2 etc..
  • 79. Department of ISE String • To create a String object. • To get the length of a string, the length property is used. alert (greet.length); // will display "4“ • Another usage of strings is to concatenate them together, the + operator has been overridden to allow for concatenation.
  • 80. Department of ISE • Many other useful methods exist within the String class, such as accessing a single character using charAt(), or searching for one using indexOf(). • Strings allow splitting a string into an array, searching and matching with split(), search(), and match() methods.
  • 81. Department of ISE Date • It is used to calculate the current date or create date objects for particular dates. • To display today’s date as a string, simply create a new object and use the toString() method.
  • 82. Department of ISE Window Object • The window object in JavaScript corresponds to the browser itself. • Through it, you can access the current page’s URL, the browser’s history, and what’s being displayed in the status bar, as well as opening new browser windows. • the alert() function is actually a method of the window object.
  • 83. Department of ISE The Document Object Model (DOM) • JavaScript is used to interact with the HTML document in which it is contained. • This is accomplished through a programming interface (API) called the Document Object Model. • According to the W3C, the DOM is a: Platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents.
  • 86. Department of ISE DOM Nodes • In DOM Tree the root or topmost object is called the Document Root. • Each element within the HTML document is called a node. If the DOM is a tree, then each node is an individual branch. • There are: 1) Element nodes, 2) Text nodes, 3) Attribute nodes
  • 88. Department of ISE • All nodes in the DOM share a common set of properties and methods. • Thus, most typical task perform in JavaScript involve finding a node, and then accessing or modifying it via properties and methods. • The most important properties are shown in below table.
  • 89. Department of ISE Some Essential Node Object Properties
  • 90. Department of ISE Document Object • The DOM document object is the root JavaScript object representing the entire HTML document. • It contains some properties and methods that we will use extensively in development and is globally accessible as document. • Accessing the properties is done through the dot notation.
  • 91. Department of ISE Some Essential Document Object Methods
  • 92. Department of ISE Accessing nodes Relationship between HTML tags and getElementByID() and getElementsByTagName()
  • 93. Department of ISE Element node Object • IDs must be unique in an HTML document,getElementByID() returns a single node. Some Essential Element Node Properties
  • 94. Department of ISE Modifying a DOM Element • document.write() method is used to create output to the HTML page from JavaScript. It always creates JavaScript at the bottom of the existing HTML page . • The modern JavaScript programmer will want to write to the HTML page, but in a particular location, not always at the bottom. • By using DOM document and HTML DOM element objects, we can do exactly that using the innerHTML property.
  • 95. Department of ISE Changing the HTML using innerHTML Out put :
  • 96. Department of ISE Changing an element’s style • We can add or remove any style using the style or className property of the Element node. • The className property is normally a better choice, because it allows the styles to be created outside the code, and thus be better accessible to designers. var commentTag = document.getElementById("specificTag"); commentTag.className = "someClassName";
  • 97. Department of ISE • HTML5 introduces the classList element, which allows you to add, remove, or toggle a CSS class on an element. label.classList.addClass("someClassName");
  • 99. Department of ISE Example to get the password out of the following input field.
  • 100. Department of ISE JavaScript Events • A JavaScript event is an action that can be detected by JavaScript. • Many of them are initiated by user actions but some are generated by the browser itself. • When an event is triggered, it will catch by JavaScript functions, which then do something in response. • In the original mechanism Events could be specified right in the HTML markup with hooks to the JavaScript code. • As more powerful frameworks were developed this original mechanism was supplanted by the listener approach.
  • 101. Department of ISE • Note : Old method uses the JavaScript right inside the HTML, while the listener technique has removed JavaScript from the markup, resulting in cleaner, easier to maintain HTML code.
  • 102. Department of ISE • Inline hooks versus the Layered Listener technique
  • 103. Department of ISE Inline Event Handler Approach • Using JavaScript within HTML makes inline. • For example, if you wanted an alert to pop-up when clicking a <div>. • In above example the HTML attribute onclick is used to attach a handler to event. When the user clicks the <div>, the event is triggered and the alert is executed. • The problem with this type of programming is that the HTML markup and the corresponding JavaScript logic are woven together. It does not make use of layers; • It does not separate content from behaviour.
  • 104. Department of ISE Listener Approach • The design principle of layers proved that it increases maintainability and simplifies markup. • The problem with the inline handler approach is that it does not make use of layers; that is, it does not separate content from behavior. • Listener approach separates all JavaScript code from the HTML markup.
  • 105. Department of ISE • There are two ways you can use listener approach i). The “old” style of registering a listener <div id="example1"></div> ii). The “new” DOM2 approach to registering listeners.
  • 106. Department of ISE • The one limitation with the inline approach is that only one handler can respond to any given element event. • By using addEventListener() shown in the above example, multiple handlers can be assigned to a single object’s event. Listening to an event with a function
  • 107. Department of ISE Event Types • There are several classes of event, with different types of event within each class specified by the W3C. • The classes are 1. Mouse events 2. Keyboard events 3. Form events 4. Frame events. i). Mouse events • Mouse events are defined to capture a range of interactions driven by the mouse. • These can be further categorized as mouse click and mouse move events.
  • 108. Department of ISE Mouse Events in JavaScript ii). Keyboard Events
  • 109. Department of ISE ii). Keyboard Events <input type="text" id="keyExample"> •The input box above, could be listened to and each key pressed echoed back to the user as an alert.
  • 110. Department of ISE Keyboard Events in JavaScript
  • 111. Department of ISE iii). Form Events • Through Forms user input is collected and transmitted to the server. • The events triggered by forms allow us to do some timely processing in response to user input. • The most common JavaScript listener for forms is the onsubmit event.
  • 112. Department of ISE • In the below example we listen for that event on a form with id loginForm. • If the password field (with id pw) is blank, we prevent submitting to the server using preventDefault() and alert the user. Exmaple Catching the onsubmit event and validating a password to not be blank
  • 113. Department of ISE Form Events in JavaScript
  • 114. Department of ISE iv). Frame Events • Frame events are the events related to the browser frame that contains your web page. • The most important event is the onload event, which tells us an object is loaded and therefore ready to work with. • However, a problem can occur if the JavaScript tries to reference a particular <div> in the HTML page that has not yet been loaded. • If the code attempts to set up a listener on this not-yet-loaded <div>, then an error will be triggered. For this reason it is common practice to use the window.onload event to trigger the execution of the rest of the page’s scripts.
  • 115. Department of ISE • The above code will only run once the page is fully loaded and therefore all references to the page’s HTML elements will be valid.
  • 116. Department of ISE Frame Events in JavaScript
  • 117. Department of ISE Forms • Consider a basic HTML form for a login example
  • 118. Department of ISE Validating Forms • User form input should be validated on both the client side and the server side. • Form validation is one of the most common applications of JavaScript. • Writing code to prevalidate forms on the client side will reduce the number of incorrect submissions, thereby reducing server load. • There are a number of common validation activities including email validation, number validation, and data validation.
  • 119. Department of ISE Empty Field Validation • A common application of a client-side validation is to make sure the user entered something into a field. • To check for an empty field in JavaScript is to compare a value to both null and the empty string ("") to ensure it is not empty.
  • 120. Department of ISE Number Validation Submitting Forms • Submitting a form using JavaScript requires having a variable for the form element. • Once the variable, say, formExample is acquired, one can simply call the submit() method: • This is often done in conjunction with calling preventDefault() on the onsubmit event.