2. Introduction
• JavaScript is scripting language
It enhances functionality and appearance
Makes pages more dynamic and interactive
Webpages give immediate response without contacting a server
Customization is possible on the basis of users input
Browser has to have a built-in (JavaScript) interpreter
Foundation for complex server-side scripting
U-4
Javascript
-
Prof.
D.
P.
Mishra
3. Introduction ..
JavaScript is Netscape’s cross-platform, object-based scripting language
JavaScript is not Java.
JavaScript is a high-level, interpreted programming language.
They are similar in some ways but fundamentally different in others.
First appeared: December 4, 1995; 24 years ago
Developed by :
Netscape Corporation,
Mozilla Foundation,
Ecma International
U-4
Javascript
-
Prof.
D.
P.
Mishra
5. Why use client-side programming?
• Client-side scripting (JavaScript) benefits:
Usability: can modify a page without having to post
back to the server (faster UI)
Efficiency: can make small, quick changes to page
without waiting for server
Event-Driven: can respond to user actions like clicks
and key presses
U-4
Javascript
-
Prof.
D.
P.
Mishra
6. Server-side programming (PHP)
benefits:
Security: has access to server's private data; client
can't see source code
Compatibility: not subject to browser compatibility
issues
Power: can write files, open connections to servers,
connect to databases, ...
U-4
Javascript
-
Prof.
D.
P.
Mishra
7. What is Javascript?
A lightweight scripting/programming language ("scripting language")
used to make web pages interactive
insert dynamic text into HTML (ex: user name)
react to events (ex: page load user click)
get information about a user's computer (ex: browser type)
perform calculations on user's computer (ex: form validation)
• a web standard (but not supported identically by all browsers)
• NOT related to Java other than by name and some syntactic
similarities
U-4
Javascript
-
Prof.
D.
P.
Mishra
8. Event-driven programming
split breaks apart a string into an array
using a delimiter
can also be used with regular expressions (seen
later)
join merges an array into a single string,
placing a delimiter between them
U-4
Javascript
-
Prof.
D.
P.
Mishra
9. A JavaScript statement: alert
• a JS command that pops up a dialog box with a message
U-4
Javascript
-
Prof.
D.
P.
Mishra
alert("IE6 detected. Suck-mode enabled.");
JS
10. Event-driven programming
• You are used to programs start with a main
method (or implicit main like in PHP)
• JavaScript programs instead wait for user
actions called events and respond to them
• Event-driven programming: writing programs
driven by user events
• Let's write a page with a clickable button that
pops up a "Hello, World" window...
U-4
Javascript
-
Prof.
D.
P.
Mishra
11. Javascript vs Java
• Javascript is interpreted, not compiled
• more relaxed syntax and rules
fewer and "looser" data types
variables don't need to be declared
errors often silent (few exceptions)
• key construct is the function rather than the class
"first-class" functions are used in many situations
• contained within a web page and integrates with its HTML/CSS
content
U-4
Javascript
-
Prof.
D.
P.
Mishra
12. Relation of java with javascript
• Not Related!
• Java and JavaScript are two completely different
languages in both concept and design!
• Java (developed by Sun Microsystems) is a powerful and
much more complex programming language - in the same
category as C and C++.
• JavaScript is the most popular scripting language on the
internet, and works in all major browsers, such as
Internet Explorer, Mozilla, Firefox, Netscape, Opera
U-4
Javascript
-
Prof.
D.
P.
Mishra
13. Types of JavaScript
There’re 2 types:
* Navigator’s JavaScript, also called client-side
JavaScript
* LiveWire JavaScript, also called server-side
JavaScript
U-4
Javascript
-
Prof.
D.
P.
Mishra
14. Embeding Javascript in HTML
• By using the SCRIPT tag
• By specifying a file of JavaScript code
• By specifying a JavaScript expression as the
value for an HTML attribute
• By using event handlers within certain other
HTML tags
U-4
Javascript
-
Prof.
D.
P.
Mishra
15. Script Tag
The <SCRIPT> tag is an extension to HTML that
can enclose any number of JavaScript statements
as shown here:
<SCRIPT>
JavaScript statements...
</SCRIPT>
A document can have multiple SCRIPT tags, and
each can enclose any number of JavaScript
statements.
U-4
Javascript
-
Prof.
D.
P.
Mishra
16. Comment in JavaScript
• <SCRIPT>
<!-- Begin to hide script contents from old
browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>
U-4
Javascript
-
Prof.
D.
P.
Mishra
17. First Hello World Program
<html>
<body>
<script language="JavaScript">
document.write(“Hello, World!”)
</script>
</body>
</html>
U-4
Javascript
-
Prof.
D.
P.
Mishra
18. External JavaScript Code
• The SRC attribute of the <SCRIPT> tag lets you
specify a file as the JavaScript source (rather
than embedding the JavaScript in the HTML).
• This attribute is especially useful for sharing
functions among many different pages.
U-4
Javascript
-
Prof.
D.
P.
Mishra
20. JavaScript Varirables
• Variables are used to store data.
• A variable is a "container" for information you want
to store.
• A variable's value can change during the script.
• You can refer to a variable by name to see its value
or to change its value.
• Rules for variable names:
Variable names are case sensitive
They must begin with a letter or the underscore character
strname – STRNAME (not same)
U-4
Javascript
-
Prof.
D.
P.
Mishra
23. Comparison Operators
U-4
Javascript
-
Prof.
D.
P.
Mishra
Operator Description Example
== is equal to 5==8 returns false
=== is equal to (checks for both
value and type)
x=5
y="5"
x==y returns true
x===y returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true
24. Cautions ..
• JavaScript is very case sensitive
• Use separate lines for each command
• Be careful with parenthesis and quotes
• Use single quotes within double quotes
• Use a semi-colon after commands as shown in examples
U-4
Javascript
-
Prof.
D.
P.
Mishra
27. U-4
Javascript
-
Prof.
D.
P.
Mishra
<html>
<script language="JavaScript">
var ans = 0;
var firstnum = 0;
var secondnum = 0;
firstnum = prompt("Enter the first number",0);
secondnum = prompt("Enter the second number",0);
ans = firstnum * secondnum;
document.write(ans);
</script>
</html>
The JavaScript var (for variable) can be
used to define a field (note that you can
eliminate the command var and it will
still work). In this example, I have
defined three variables and given them
all an initial value of 0.
The prompt can be used to take in
data. The message in quotes is
used to ask the user for input and
the 0 indicates it is numeric
input. Note that the data that was
keyed in with the first prompt
was assigned to firstnumand the
data that was keyed in with the
second prompt was assigned to
secondnum.
ans = firstnum *
secondnum;
This takes the two numbers
stored in firstnum and
secondnum and multiplies
them together. The results
are stored in ans.
document.write(ans);
I am now using the write
method to put ans to the
screen. Note that ans is a
variable, not a literal so it is not
enclosed in quotes.
31. JavaScript Popup Boxes
• Alert Box
An alert box is often used if you want to make sure information comes
through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
<script>
alert("Hello World!")
</script>
U-4
Javascript
-
Prof.
D.
P.
Mishra
32. JavaScript Popup Boxes - 2
• Confirm Box
A confirm box is often used if you want the user to verify or accept
something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
U-4
Javascript
-
Prof.
D.
P.
Mishra
33. JavaScript Popup Boxes - 3
• Prompt Box
A prompt box is often used if you want the user to input a value before
entering a page.
When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK“, the box returns the input value. If the user clicks
"Cancel“, the box returns null.
U-4
Javascript
-
Prof.
D.
P.
Mishra
36. U-4
Javascript
-
Prof.
D.
P.
Mishra
<html>
<script language="JavaScript">
var ans = 0;
var firstnum = 0;
var secondnum = 0;
firstnum = prompt("Enter the first number",0);
secondnum = prompt("Enter the second number",0);
ans = firstnum * secondnum;
document.write("The answer is ", ans);
</script>
</html>
The only change here is in the
document.write where I am writing the
literal “The answer is ” and then the
variable answer, ans. Note that I
separated the literal and the variable
with a comma.
37. JS Examples -1
Write a script to find Y=20x+12 where x=3
<script>
x=3
y=20*x+12
alert(y)
</script>
U-4
Javascript
-
Prof.
D.
P.
Mishra
39. Control Statement/Flow
• Elements of code that define an individual action
• Like most programming languages, JavaScript has three control structures:
Serial Sequence structure
Any individual non-selection and non-repetition statement falls into this
category: line by line execution of code like individual calculation, input or
output statement, type conversion, etc.
Selection structure: three in JavaScript
if
if…else
switch
Repetition structure: four in JavaScript
while
do…while
for
for…in
U-4
Javascript
-
Prof.
D.
P.
Mishra
40. Serial/Sequential
• Sequential execution
Statements execute in the order they are written
• Transfer of control
Next statement to execute may not be the next one in
sequence
U-4
Javascript
-
Prof.
D.
P.
Mishra
add grade to total total = total + grade;
add 1 to counter counter = counter + 1 ;
41. U-4
Javascript
-
Prof.
D.
P.
Mishra
if Selection Statement (1)
• Indicate action only when the condition evaluates to true
• JavaScript Format:
if ( boolean expression )
statement;
• Example:
if (grade>= 60)
document.writeln(“Passed”);
grade >= 60 true
false
print
“Passed”
42. U-4
Javascript
-
Prof.
D.
P.
Mishra
if Selection Statement (2)
• Multiple actions are performed when the condition is true
• JavaScript Format:
if ( boolean expression )
{
statementOne;
statementTwo;
:
}
• Example:
if (grade>= 60)
{
document.writeln("<h1 style="color:red">" +
"Congratulations!</h1>");
document.writeln("<h2> You Passed!</h2>");
}
46. Nested if…else Selection
Statement
• When we have one decision criterion but with multiple and mutually
exclusive range of values
If student = “Senior” …
Else if student = “Junior” …
Else if student = “Sophomore” …
Else …
Switch clause can be used instead
• When we have more than one decision criterion
for example when making decisions based on combined values of variable “age” and
“income”:
Logic errors vs. syntax errors
Can be simplified by using logical AND (&&) , OR (||) operators
In class example
U-4
Javascript
-
Prof.
D.
P.
Mishra
49. Types of errors in programming
There are three types of errors in programming:
• Syntax Errors
• Runtime Errors,
• Logical Errors.
U-4
Javascript
-
Prof.
D.
P.
Mishra
50. Syntax Error
• Syntax errors, also called parsing errors,
• Occur at compile time in traditional programming languages
• and at interpret time in JavaScript
• For example, the following line causes a syntax error because it is
missing a closing parenthesis.
• When syntax error occurred only the code contained within the same
thread as the syntax error is affected and the rest of the code in other
threads gets executed
U-4
Javascript
-
Prof.
D.
P.
Mishra
51. Runtime Errors
• Runtime errors, also called exceptions,
• occur during execution after compilation/interpretation.
• For example, the following line causes a runtime error because here
the syntax is correct, but at runtime, it is trying to call a method that
does not exist.
• Exceptions affect the thread in which they occur, allowing other
JavaScript threads to continue normal execution
U-4
Javascript
-
Prof.
D.
P.
Mishra
52. Logical Errors
• Logic errors can be the most difficult type of errors to track down.
• These errors are not the result of a syntax or runtime error.
• Instead, they occur when you make a mistake in the logic that drives
your script and you do not get the result you expected
• You cannot catch those errors, because it depends on your business
requirement what type of logic you want to put in your program.
U-4
Javascript
-
Prof.
D.
P.
Mishra
53. The try...catch...finally Statement
• The latest versions of JavaScript added exception handling
capabilities.
• JavaScript implements the try...catch...finally construct as well as
the throw operator to handle exceptions.
• You can catch programmer-generated and runtime exceptions, but
you cannot catch JavaScript syntax errors
U-4
Javascript
-
Prof.
D.
P.
Mishra
54. <script
type="text/javascript">
<!--
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an
exception occurs
[break;]
}
[ finally {
// Code that is always
executed regardless of
// an exception occurring
}]
//-->
</script>
U-4
Javascript
-
Prof.
D.
P.
Mishra
55. Try – catch - finally
• The try block must be followed by either exactly one catch block or
one finally block or one of both.
• When an exception occurs in the try block, the exception is placed
in e and the catch block is executed.
• The optional finally block executes unconditionally after try/catch
U-4
Javascript
-
Prof.
D.
P.
Mishra
56. <html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form >
<input type="button" value="Click Me" onclick="myFunc();" />
</form >
</body>
</html>
U-4
Javascript
-
Prof.
D.
P.
Mishra
Code without Try Catch
57. <head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form >
<input type="button" value="Click Me" onclick="myFunc();" />
</form >
</body>
</htm l>
U-4
Javascript
-
Prof.
D.
P.
Mishra
58. You can use finally block which will always execute
unconditionally after the try/catch.
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>.
U-4
Javascript
-
Prof.
D.
P.
Mishra
59. The throw Statement
• You can use throw statement to raise your built-in exceptions or your
customized exceptions.
• Later these exceptions can be captured
• After catching you can take an appropriate action.
U-4
Javascript
-
Prof.
D.
P.
Mishra
60. Example of throw statement
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}
else
{
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
U-4
Javascript
-
Prof.
D.
P.
Mishra
61. The on error Method
• The onerror event handler was the first feature to facilitate error
handling in JavaScript.
• The error event is fired on the window object whenever an exception
occurs on the page.
• The onerror event handler provides three pieces of information to
identify the exact nature of the error −
• Error message − The same message that the browser would display
for the given error
• URL − The file in which the error occurred
• Line number− The line number in the given URL that caused the
error
U-4
Javascript
-
Prof.
D.
P.
Mishra
62. Example of on error method
<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function () {
alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form >
<input type="button" value="Click Me" onclick="myFunc();" />
</form >
</body>
</htm l>
U-4
Javascript
-
Prof.
D.
P.
Mishra
63. <html>
<head>
<script type="text/javascript">
<!--
window.onerror = function (m sg, url, line) {
alert("Message : " + m sg );
alert("url : " + url );
alert("Line num ber : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form >
<input type="button" value="Click Me" onclick="m yFunc();" />
</form >
</body>
</htm l>
U-4
Javascript
-
Prof.
D.
P.
Mishra
65. What is object ?
• Object - a material or thing that can be seen and touched,
• Look around right now and you'll find many examples of real-
world objects: Notebook, Pen, chalk, Duster, table, chair, light, fan
... As you do, you'll notice that real-world objects vary in
complexity;
• In programming object refers to a particular instance of a
class, where the object can be a combination of variables,
functions, and data structure
U-4
Javascript
-
Prof.
D.
P.
Mishra
66. In JavaScript, almost
"everything" is an object.
• Booleans can be objects (if defined with the new keyword)
• Numbers can be objects (if defined with the new keyword)
• Strings can be objects (if defined with the new keyword)
• Dates are always objects
• Maths are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects
U-4
Javascript
-
Prof.
D.
P.
Mishra
All JavaScript values, except primitives, are objects.
5 primitive Data types:
• undefined ,
• null ,
• boolean ,
• string and
• number
67. JavaScript Primitives
• A primitive value is a value that has no properties or
methods.
• A primitive data type is data that has a primitive value.
• JavaScript defines 5 types of primitive data types:
• string
• number
• boolean
• null
• undefined
U-4
Javascript
-
Prof.
D.
P.
Mishra
68. JavaScript Objects
• JS has built-in objects
E.g. Math, Date
• Browser creates objects
These model the document (web page)
• You can create your own objects
Objects are built on-the-fly
U-4
Javascript
-
Prof.
D.
P.
Mishra
70. Built in Objects…
• String has many methods
indexOf, charAt, substring, etc.
Also has methods to create HTML strings
var st = new String(“I’m big and bold!”);
var st1 = st.bold();
var out = st1.big();
Gives
<big><bold>I’m big and bold!</bold></big>
U-4
Javascript
-
Prof.
D.
P.
Mishra
72. Date object
var dt = new Date( ); gives the current
date
• Date has getX and setX methods for X = FullYear,
Month, Day, Hours, Minutes, Seconds and Milliseconds
• Formatting methods return date as a string
toString( )
toGMTString( ) – converts to a string according to
Greenwich time.
toLocaleString( )
U-4
Javascript
-
Prof.
D.
P.
Mishra
73. Date Example
<html>
<head>
<title>Time page</title>
</head>
<body>
Time when page was loaded:
<script language="JavaScript">
now = new Date();
document.write(now.toString() +
"<br><br>");
document.write(now.getHours() + ":" +
now.getMinutes() + ":" +
now.getSeconds());
</script>
</body>
</html>
U-4
Javascript
-
Prof.
D.
P.
Mishra
Here, set to the
current date and
time using the
default constructor
toString displays the
full date using month
and day names
using the get methods,
can display desired
components of the
date/time
75. Array Objects
• JS arrays are objects!
• Can be created with new keyword
var newAr = new Array(“one”, “two”, “three”, 4);
var newAr = new Array(3);
• Can also be created with array literal
var newAr = [“one”, 2, “three”];
Note :
The square brackets, not braces
Values of different data types can be mixed
U-4
Javascript
-
Prof.
D.
P.
Mishra
76. Array Object ..
• Array elements are accessed as in Java: var first = newAr[0];
• Can be multi-dimensional as in Java
• .length property gives the current length = the highest subscript
to which a value has been assigned
• Can be read or written
• Arrays are not fixed in length
By setting the length property to a smaller value you
shrink the array
Space is not reserved for each element, only those defined
(assigned)
var a = new Array(5); // all are undefined
a[100] = 2; // has only 1 defined
U-4
Javascript
-
Prof.
D.
P.
Mishra
77. Arrays ..
• Flexibility of arrays allows many methods;
var list = [2, 4, 6, 8, 10]
slice() – returns part of an array: list.slice(1,3) => array [4, 6]
concat( ) – concatenates new elements to the end of the array; returns
new array: list.concat(12) => [2, 4, 6, 8, 10, 12]
join( ) – creates a string from the array elements, separated by commas (or
specified delimiter): list.join(“ : ”) => “2 : 4 : 6 : 8: 10”
reverse( ) – reverses order of the array elements; affects calling array
sort( ) – converts elements to strings, sorts them alphabetically (or you
can specify another order as a function); affects calling array
push( ), pop( ) – add/delete elements to the high end of array
unshift( ), shift( ) – add/delete elements at the beginning of the array
U-4
Javascript
-
Prof.
D.
P.
Mishra
78. Associative Array
• Array with non-numeric indices
• Also called a hash
• Created as Object and filled using index value
var myHash = new Object();
myHash[“me”] = “Instructor”;
myHash[“you”] = “Student”;
for (var i in myHash)
alert (i + "-" + myHash[i]);
U-4
Javascript
-
Prof.
D.
P.
Mishra
80. Boolean Object
• The Boolean and Number objects are object wrappers for boolean
true/false values and numbers, respectively
• When a boolean value is required in a JavaScript program, JavaScript
automatically creates a Boolean object to store the value
• JavaScript programmers can create Boolean objects explicitly
var b = new Boolean( booleanValue );
booleanValue specifies the value of the Boolean object (true or
false).
If booleanValue is false, 0, null, Number.NaN or the empty string
(""), or if no argument is supplied, the new Boolean object contains
false
Otherwise, the new Boolean object contains true
U-4
Javascript
-
Prof.
D.
P.
Mishra
82. Math Object
• The math object provides you properties and methods for
mathematical constants and functions.
• Unlike other global objects, Math is not a constructor.
• Math object allows to perform mathematical operation on numbers
Syntax to call the properties and methods –
var pi_val = Math.PI;
var sine_val = Math.sin(30);
U-4
Javascript
-
Prof.
D.
P.
Mishra
A constructor is a special method that is used to initialize a newly created object and is
called just after the memory is allocated for the object.
83. U-4
Javascript
-
Prof.
D.
P.
Mishra
Method Description Examples
abs( x ) absolute value of x abs( 7.2 ) is 7.2
abs( 0.0 ) is 0.0
abs( -5.6 ) is 5.6
ceil( x ) rounds x to the smallest integer not
less than x
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x
(x in radians)
cos( 0.0 ) is 1.0
exp( x ) exponential method ex
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( x ) rounds x to the largest integer not
greater than x
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
min( x, y ) smaller value of x and y min( 2.3, 12.7 ) is 2.3
min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y (xy
) pow( 2.0, 7.0 ) is 128.0
pow( 9.0, .5 ) is 3.0
round( x ) rounds x to the closest integer round( 9.75 ) is 10
round( 9.25 ) is 9
sin( x ) trigonometric sine of x
(x in radians)
sin( 0.0 ) is 0.0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x
(x in radians)
tan( 0.0 ) is 0.0
85. What is AJAX ?
• AJAX - Asynchronous JavaScript and XML
• Not a language itself
• A group of related existing technologies compiled together
or technique to make web pages feel more responsive
• Makes interactive web pages by providing a way for the
web page to interact with the server
• AJAX is a framework
U-4
Javascript
-
Prof.
D.
P.
Mishra
88. Based on Internet Standards
• XHTML/HTML and CSS
To display the data
• JavaScript (XMLHttpRequest calls)
To exchange data asynchronously with the server
• XML
To tranfer the data
• DOM (document object model)
To navigate the hierarchy of X/HTML elements
U-4
Javascript
-
Prof.
D.
P.
Mishra
89. X/HTML and CSS
• Elements are identified in the X/HTML code that will be worked with
by the JavaScript
• These provide the visual layout and structure for how the XML data
will be displayed (performed on the client machine)
• CSS provides the styling
U-4
Javascript
-
Prof.
D.
P.
Mishra
90. JavaScript/XMLHttp Request
• Provides connection between the X/HTML element(s) and how they
behave
• Sends XMLHttpRequests on demand when the user creates events
• Handles events both from the user and the replies from the server
• Can parse XML data and map it to data objects needed in the
JavaScript
• Updates the X/HTML elements as needed
U-4
Javascript
-
Prof.
D.
P.
Mishra
91. XML
• Provides format for data transfer between the JavaScript and the
server
U-4
Javascript
-
Prof.
D.
P.
Mishra
92. DOM
• Two DOMs involved
One for the elements in the X/HTML
One for the elements in the XML file
• Defines the logical structure of the documents
• Can be used by any programming language
• Used for navigating around the tree structure
• Provides quick access for changing/modifying elements
U-4
Javascript
-
Prof.
D.
P.
Mishra
93. XMLHttpRequest
• Object used for fetching/returning data
• Can be synchronous or asynchronous— AJAX uses it
asynchronously
• Allows the web pages to get more data from the server incrementally
and asynchronously while the user is doing other things
Examples are
• Gmail, which continuously asks the server for new mail and
• Google Maps, which update only the new parts of a map when
the user mouses or clicks on a new point
U-4
Javascript
-
Prof.
D.
P.
Mishra
94. Advantages
• Interactivity
– Asynchronous transmission of data back and forth
• Bandwidth usage
– Smaller payload
• Encourages modularization
– Function, data sources, structure and style
• Allows non-related technologies to work together
- (server-side languages, databases, client-side languages, etc.)
U-4
Javascript
-
Prof.
D.
P.
Mishra
95. Disadvantages
• Difficult to debug because it is asynchronous
• Search engines can’t index/optimize
• Browsers handle XHRs differently—Internet Explorer didn’t have a
native one till version 7 (presently on version 8)
• Back button and bookmarks may not work as expected
• May experience response time/latency problems if there are
many frequent updates
U-4
Javascript
-
Prof.
D.
P.
Mishra
96. Uses for AJAX
• Real-time form data validation when server-side information is
required
• Autocompletion (again when server-side info from a database, for
example, is needed)
• Sophisticated user interface controls and effects such as progress
bars
• Getting current data without reloading a full page
U-4
Javascript
-
Prof.
D.
P.
Mishra
97. Conclusion
• AJAX is a technique for creating fast, dynamic, responsive web pages
• AJAX applications are browser- and platform-independent
U-4
Javascript
-
Prof.
D.
P.
Mishra
99. JavaScript Event Handlers
• JavaScript deals with events with commands called event
handlers.
• In JavaScript, if the user clicks on a button, the onClick() event
handler will take note of the action and perform whatever duties
it was assigned.
listing of Event Handlers on next slide.
U-4
Javascript
-
Prof.
D.
P.
Mishra
100. Event Handlers
Event What it Handles Event What it Handles
onAbort User aborted
loading the page
onLoad Object finished
loading
onBlur User left the object onMouseOver Cursor moved
over an object
onChange User changed the
object
onMouseOut Cursor moved
off an object
onClick User clicked on an
object
onSelect User selected
the contents of
an object
onError Script encountered
an error
onSubmit User submitted
a form
onFocus User made an
object active
onUnload User left the
window
U-4
Javascript
-
Prof.
D.
P.
Mishra
101. Event Example
• Some Web designers like to have special messages pop-up in the
Status Bar when a mouse passes over a Hypertext link.
• We will use a onMouseOver trick for this one.
• Code is on the next slide.
U-4
Javascript
-
Prof.
D.
P.
Mishra
102. onMouseOver Code inside the
<Body> Tag
• Used Hyperlink to Hotbot and give it a cool description for
the status bar.
Note: You can't
have a Scrolling
Message and
this too!
U-4
Javascript
-
Prof.
D.
P.
Mishra
103. Tips for Writing JavaScript
• Use comments throughout to help you
understand the program. <!-- comments -->
• Use indented text to make your code easier to
read and follow.
• JavaScript is case-sensitive, be careful.
• Include HTML comment tag to hide JavaScript
from older browsers that don’t support the code.
• Test your JavaScript program with several
browsers if possible.
U-4
Javascript
-
Prof.
D.
P.
Mishra
104. JavaScript programming
• There are many JavaScripts on the Web that you
can copy and/or modify quite easily to fit your
needs
• JavaScript programming often consist of:
Finding effects on a page that you want to duplicate
Locating the code that performs the effect – use
View/Source in your browser
Cutting the code from the original page and embedding
it in your page
Getting it to work in the new environment
U-4
Javascript
-
Prof.
D.
P.
Mishra
106. CSS
• CSS is a language that describes the style of an HTML document.
• CSS describes how HTML elements should be displayed.
Example :
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
p {
font-family: verdana;
font-size: 20px;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
107. CSS Syntax and Selectors
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
• A CSS rule-set consists of a selector and a declaration block:
• The selector points to the HTML element you want to style.
• The declaration block contains one or more declarations separated by
semicolons.
• Each declaration includes a CSS property name and a value, separated by
a colon.
• A CSS declaration always ends with a semicolon, and declaration blocks
are surrounded by curly braces.
108. Example
• In the following example all <p> elements will be center-aligned,
with a red text color:
p {
color: red;
text-align: center;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
109. The element Selector
• The element selector selects elements based on the element name.
• You can select all <p> elements on a page like this (in this case, all
<p> elements will be center-aligned, with a red text color):
• Example
p {
text-align: center;
color: red;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
110. The id Selector
• The id selector uses the id attribute of an HTML element to select a
specific element.
• The id of an element should be unique within a page, so the id selector is
used to select one unique element!
• To select an element with a specific id, write a hash (#) character,
followed by the id of the element.
• The style rule below will be applied to the HTML element with
id="para1":
Example
#para1 {
text-align: center;
color: red;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
111. The class Selector
• The class selector selects elements with a specific class attribute.
• To select elements with a specific class, write a period (.) character,
followed by the name of the class.
• In the example below, all HTML elements with class="center" will be
red and center-aligned:
Example
.center {
text-align: center;
color: red;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
112. The class Selector ..
• You can also specify that only specific HTML elements should be
affected by a class.
• In the example below, only <p> elements with class="center" will be
center-aligned:
Example
p.center {
text-align: center;
color: red;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
113. Three Ways to Insert CSS
There are three ways of inserting a style sheet:
• External style sheet
• Internal style sheet
• Inline style
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
114. External Style Sheet
• With an external style sheet, you can change the look of an entire
website by changing just one file!
• Each page must include a reference to the external style sheet file
inside the <link> element. The <link> element goes inside the
<head> section:
Example
• <head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
115. mystyle.css
• An external style sheet can be written in any text editor. The file
should not contain any html tags. The style sheet file must be saved
with a .css extension.
• Here is how the "mystyle.css" looks:
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
116. Internal Style Sheet
• An internal style sheet may be used if one single page has a unique style.
• Internal styles are defined within the <style> element, inside the <head> section
of an HTML page
Example
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
117. Inline Styles
• An inline style may be used to apply a unique style for a single
element.
• To use inline styles, add the style attribute to the relevant element.
The style attribute can contain any CSS property.
• The example below shows how to change the color and the left
margin of a <h1> element:
Example
<h1 style="color:blue;margin-left:30px;">This is a heading</h1>
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
118. Multiple Style Sheets
• If some properties have been defined for the same selector (element) in
different style sheets, the value from the last read style sheet will be
used.
Example
• Assume that an external style sheet has the following style for the <h1>
element:
h1 {
color: navy;
}
then, assume that an internal style sheet also has the following style for
the <h1> element:
h1 {
color: orange;
}
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
119. • If the internal style is defined after the link to the external style
sheet, the <h1> elements will be "orange":
Example
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
color: orange;
}
</style>
</head>
U-3
Understanding
WWW
-
Prof.
D.
P.
Mishra
120. Div and Span Tag
U-4
Javascript
-
Prof.
D.
P.
Mishra
121. Generic Containers
• Currently, we know how to modify the properties of HTML tags
using style sheets
• But, we can only modify the tags and what they contain
Can’t modify a group of tags as one
• The generic containers, <span> and <div>, allow us to group tags or
words
U-4
Javascript
-
Prof.
D.
P.
Mishra
122. Generic Containers ..
• The generic container tags do absolutely nothing,
until they are modified by attributes.
• The <span> tag in an inline tag
Can modify the language (lang attribute), font color,
font-family, font-style, etc.
• The <div> tag is a block-level tag
Allows us to group paragraphs together with lists, etc.
Can be used to create navigation bars
U-4
Javascript
-
Prof.
D.
P.
Mishra
123. <span> Tag
• The span tag is useful for applying attributes to some text
ex. I love chocolate-covered espresso beans
CSS:
span.chocolate {
font-family: Times;
color: #330;
}
U-4
Javascript
-
Prof.
D.
P.
Mishra
HTML:
I love <span class = “chocolate”> chocolate-covered espresso beans</span>
124. <span> ..
• <span> can be contained within block-level and inline-
level elements
• The attributes of <span> are:
id : the id from the style sheet
class : the class from the style sheet
lang : language of the text
dir : specifies the direction of text (ltr, rtl)
U-4
Javascript
-
Prof.
D.
P.
Mishra
125. Using <span>
• Span should not be used when there is an
appropriate standard html tag
e.g do not use <span> to italicize text
Use the <i> tag
The <i>, <b>, <em> etc. also have attributes
Including <style>, <lang> etc.
<i style =“color: red; font-family: Courier”>
• You do not have to specify a CSS rule to use span
I love <span style = “color: #330; font-family: Times”>
chocolate-covered espresso beans</span>
U-4
Javascript
-
Prof.
D.
P.
Mishra
126. <span> Cont ..
• <span> should be used only to modify small
portions of text
• Do not use <span> to modify all of a paragraph
• If you do need to use span, and will need the
same modifications more than once or twice, add
a class to your style sheet
• Also helpful to use a style sheet so that you only
have to modify a single file to change the way the
document appears
U-4
Javascript
-
Prof.
D.
P.
Mishra
127. <div> Tag
• Probably the most common use for the <div> tag is for navigation
bars
• <div> is a block-level tag (like a paragraph)
• Can contain any number of block-level tags or inline tags
Can group paragraphs, with lists, with tables, e.g.
U-4
Javascript
-
Prof.
D.
P.
Mishra
128. <div> tag
• <div> tags will most often be used inside the <body> tag and inside
other <div> tags
Can be nested
• Often <div> tags are modified using the id attribute, rather than
class
You only have one navigation bar, e.g.
The properties you want for a certain portion of your page are unique
U-4
Javascript
-
Prof.
D.
P.
Mishra
129. Simple Navigation Menu
CSS
div#sidebar {
float:left;
background-color: #ccf;
width: 10%;
}
HTML
<div id = “sidebar”>
<ul>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ul>
</div>
130. U-4
Javascript
-
Prof.
D.
P.
Mishra
Questions Appeared in Previous year University Examination:
Nov – Dec 2013
1. What is AJAX? – 2m
2. Explain Different types of objects available in JavaScript – 7M
3. What are the external, Internal and Inline Style sheets in CSS ?
4. Write about the try-catch – throw statement of JavaScript
Nov – Dec 2014
1. Write features of JavaScript– 2m
2. What are the different methods available in JavaScript to take input from the user ? Explain.
7M
3. How does JavaScript handles exceptions ? Explain with example. – 7M
April-May 2014
1. How to write comment in JavaScript – 2m -- //
2. Describe the types of popup boxes used in JavaScript- 7M
3. Describe exception handling using catch statement in JavaScript- 7M
4. Write short note on cascading style sheets- 7M
131. U-4
Javascript
-
Prof.
D.
P.
Mishra
Questions Appeared in Previous year University Examination …
Nov – Dec 2015
1. Give the output for the following
<html>
<body>
<%
sometext=“Bye!”
Max=len(sometext)
For i=0 to max
Newtext=left(sometext , i)
Response.write(StrReverse(newtext))
Response.write(“<br>”);
Next
%> – 2m
2. Draw the hierarchy of javascript built in objects and explain each one briefly - 7M
3. Explain in details CSS border and CSS Outline – 7M
4. Explain about the objects that helps AJAX reload parts of webpage without reloading whole webpage - 7M
Nov – Dec 2016
1. What is AJAX? – 2m
2. Discuss in brief various operators of javascript - 7M
3. Illustrate with suitable example the concept of control statements, try-catch and throw statements in javascript – 7M
4. Write a javascript making use of class selector, div and span tag - 7M
132. U-4
Javascript
-
Prof.
D.
P.
Mishra
Questions Appeared in Previous year University Examination …
April –May 2017
1. Write the names of popup boxes in JavaScript – 2m
2. Write the code for a web page, using javascript, to print ‘n’ terms of Fibonacci Series- 7M
3.What are the built in objects available in javascript? Explain each using suitable example– 7M
4. Explain the role of CSS in web development. What are the various types of style sheets ? - 7M
Nov – Dec 2018
1. What is AJAX? – 2m
2. Give examples of External style sheet, Internal Style sheet, and Inline styles - 7M
3.Describe javascript Pop up boxes with proper syntax– 7M
4. Define javascript Math objects, their properties and methods with suitable example.- 7M
133. Learn Following Technologies
• Node.js/ Express.js/ StrongLoop/ LoopBack / Serverless
(AWS Lambda) / Python / Django / Flask / Java / J2EE
• Third party Javascript library and framework like -
ReactJS/ React Native/ AngularJS (2,4,5) / Typescript/
Vue.js / ES6
• Databases like MongoDB or/and MySQL
• Familiarity in HTML5, CSS3, JSP, Servlets
U-4
Javascript
-
Prof.
D.
P.
Mishra