SlideShare ist ein Scribd-Unternehmen logo
1 von 133
Downloaden Sie, um offline zu lesen
Unit-4 JavaScript
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
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
Client Side Scripting
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
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
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
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
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
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
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
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
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
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
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
First Hello World Program
<html>
<body>
<script language="JavaScript">
document.write(“Hello, World!”)
</script>
</body>
</html>
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
Example
• <HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
………….
</SCRIPT>
</HEAD>
<BODY>
………….
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
Arithmetic Operators
U-4
Javascript
-
Prof.
D.
P.
Mishra
Operator Description Example Result
+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
Assignment Operators
U-4
Javascript
-
Prof.
D.
P.
Mishra
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
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
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
U-4
Javascript
-
Prof.
D.
P.
Mishra
U-4
Javascript
-
Prof.
D.
P.
Mishra
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.
U-4
Javascript
-
Prof.
D.
P.
Mishra
<html>
<script language="JavaScript">
document.write("Hello World!");
alert("Hello World!");
</script>
</html>
JavaScript Basic Examples
<script>
document.write("Hello World!")
</script>  format text with HTML code - heading
<script>
alert("Hello World!")
</script>
U-4
Javascript
-
Prof.
D.
P.
Mishra
Example
<script>
x=“Hello World!”
document.write(x)
</script>
<script>
x=“ BIT STUDENT.”
document.write(“HELLO” +x)
</script>  use line break html code
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
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
Prompt Box Example
<script>
x=prompt (“Enter Your Name”, “ ”)
document.write(“Hello <br>”,+x)
</script>
U-4
Javascript
-
Prof.
D.
P.
Mishra
U-4
Javascript
-
Prof.
D.
P.
Mishra
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.
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
Examples -2
<script>
s1=12
s2=28
total=s1+s2
document.write(“Total : "+total);
</script>
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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 ;
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”
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>");
}
U-4
Javascript
-
Prof.
D.
P.
Mishra
if…else Selection Statement (1)
• Indicate different actions to be perform when condition is true or
false
grade >= 60
true
print “Failed”
false
print “Passed”
U-4
Javascript
-
Prof.
D.
P.
Mishra
if…else Selection Statement (2)
• JavaScript Format:
if ( boolean expression )
statement;
else
statement;
• JavaScript Example :
if ( grade >= 60 )
document.writeln(“Passed”);
else
document.writeln(“Failed”);
U-4
Javascript
-
Prof.
D.
P.
Mishra
if…else Selection Statement (3)
• Multiple actions
• JavaScript Format :
if ( boolean expression )
{
statementOne;
statementTwo;
:
}else
{
statementThree;
statementFour;
:
}
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
U-4
Javascript
-
Prof.
D.
P.
Mishra
while Repetition Statement (1)
• Repetition structure (loop)
 Repeat action while some condition remains true.
Product < = 1000 product = 2 * product
true
false
Errors & Exception
Handling
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
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
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
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
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
<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
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
<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
<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
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
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
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
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
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
<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
Objects in JavaScript
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
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
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
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
Objects
Date Object
GetDate()
GetTime()
GetDay()
GetMonth()
Math Object
abs(number)
log(number)
random()
String Object
fontcolor()
fontsize()
ToLowerCase()
ToUpperCase()
Window Object
alert(“message”)
confirm(“message”)
close()
JavaScript enabled browsers have built-in objects which have
properties, events and methods which can be used by JavaScript. For
example:
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
Date Object
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
Array Object
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
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
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
Boolean Object
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
Math Object
U-4
Javascript
-
Prof.
D.
P.
Mishra
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.
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
AJAX
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
How it works
U-4
Javascript
-
Prof.
D.
P.
Mishra
AJAX Interaction Provides Validation Logic
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
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
XML
• Provides format for data transfer between the JavaScript and the
server
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
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
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
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
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
Event Handling
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
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
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
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
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
CSS
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
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.
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
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
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
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
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
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
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
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
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
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
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
• 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
Div and Span Tag
U-4
Javascript
-
Prof.
D.
P.
Mishra
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
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
<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>
<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
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
<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
<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
<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
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>
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
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
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
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

Weitere ähnliche Inhalte

Ähnlich wie JavaScript

Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academyactanimation
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereLaurence Svekis ✔
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript ProgrammingRaveendra R
 
JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGArulkumar
 
Java script Basic
Java script BasicJava script Basic
Java script BasicJaya Kumari
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptxGangesh8
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scriptingpkaviya
 

Ähnlich wie JavaScript (20)

Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTING
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
JavaScript Basics with baby steps
JavaScript Basics with baby stepsJavaScript Basics with baby steps
JavaScript Basics with baby steps
 
Java script
Java scriptJava script
Java script
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
Unit 4 Java script.pptx
Unit 4 Java script.pptxUnit 4 Java script.pptx
Unit 4 Java script.pptx
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
Lecture7
Lecture7Lecture7
Lecture7
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript | Introduction
JavaScript | IntroductionJavaScript | Introduction
JavaScript | Introduction
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
Welcome to React.pptx
Welcome to React.pptxWelcome to React.pptx
Welcome to React.pptx
 

Mehr von BIT DURG

Understanding WWW
Understanding WWWUnderstanding WWW
Understanding WWWBIT DURG
 
Computer Networks
Computer NetworksComputer Networks
Computer NetworksBIT DURG
 
Computer Basics
Computer Basics Computer Basics
Computer Basics BIT DURG
 
ISDN & ATM
ISDN & ATMISDN & ATM
ISDN & ATMBIT DURG
 
Transport Control Protocol
Transport Control ProtocolTransport Control Protocol
Transport Control ProtocolBIT DURG
 
Routing Protocols
Routing ProtocolsRouting Protocols
Routing ProtocolsBIT DURG
 
Internet Protocol.pdf
Internet Protocol.pdfInternet Protocol.pdf
Internet Protocol.pdfBIT DURG
 
Intternetworking With TCP/IP
Intternetworking With TCP/IPIntternetworking With TCP/IP
Intternetworking With TCP/IPBIT DURG
 
Computer Network Basics
Computer Network BasicsComputer Network Basics
Computer Network BasicsBIT DURG
 
Types of Linux Shells
Types of Linux Shells Types of Linux Shells
Types of Linux Shells BIT DURG
 
File Access Permission
File Access PermissionFile Access Permission
File Access PermissionBIT DURG
 
Control flow and related shell cripts
Control flow and related shell criptsControl flow and related shell cripts
Control flow and related shell criptsBIT DURG
 
Basic Shell Programs
Basic Shell ProgramsBasic Shell Programs
Basic Shell ProgramsBIT DURG
 
Filters & Vi Editor
Filters & Vi EditorFilters & Vi Editor
Filters & Vi EditorBIT DURG
 
Basic Linux Commands
Basic Linux CommandsBasic Linux Commands
Basic Linux CommandsBIT DURG
 
Linux Installation
Linux InstallationLinux Installation
Linux InstallationBIT DURG
 
Basics of GNU & Linux
Basics of GNU & LinuxBasics of GNU & Linux
Basics of GNU & LinuxBIT DURG
 
National youth day
National youth dayNational youth day
National youth dayBIT DURG
 

Mehr von BIT DURG (20)

HTML_DOM
HTML_DOMHTML_DOM
HTML_DOM
 
Understanding WWW
Understanding WWWUnderstanding WWW
Understanding WWW
 
Computer Networks
Computer NetworksComputer Networks
Computer Networks
 
Computer Basics
Computer Basics Computer Basics
Computer Basics
 
ISDN & ATM
ISDN & ATMISDN & ATM
ISDN & ATM
 
Transport Control Protocol
Transport Control ProtocolTransport Control Protocol
Transport Control Protocol
 
Routing Protocols
Routing ProtocolsRouting Protocols
Routing Protocols
 
Internet Protocol.pdf
Internet Protocol.pdfInternet Protocol.pdf
Internet Protocol.pdf
 
Intternetworking With TCP/IP
Intternetworking With TCP/IPIntternetworking With TCP/IP
Intternetworking With TCP/IP
 
Computer Network Basics
Computer Network BasicsComputer Network Basics
Computer Network Basics
 
MySQL
MySQL MySQL
MySQL
 
Types of Linux Shells
Types of Linux Shells Types of Linux Shells
Types of Linux Shells
 
File Access Permission
File Access PermissionFile Access Permission
File Access Permission
 
Control flow and related shell cripts
Control flow and related shell criptsControl flow and related shell cripts
Control flow and related shell cripts
 
Basic Shell Programs
Basic Shell ProgramsBasic Shell Programs
Basic Shell Programs
 
Filters & Vi Editor
Filters & Vi EditorFilters & Vi Editor
Filters & Vi Editor
 
Basic Linux Commands
Basic Linux CommandsBasic Linux Commands
Basic Linux Commands
 
Linux Installation
Linux InstallationLinux Installation
Linux Installation
 
Basics of GNU & Linux
Basics of GNU & LinuxBasics of GNU & Linux
Basics of GNU & Linux
 
National youth day
National youth dayNational youth day
National youth day
 

Kürzlich hochgeladen

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 

Kürzlich hochgeladen (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 

JavaScript

  • 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
  • 19. Example • <HEAD> <TITLE>My Page</TITLE> <SCRIPT SRC="common.js"> …………. </SCRIPT> </HEAD> <BODY> …………. 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
  • 21. Arithmetic Operators U-4 Javascript - Prof. D. P. Mishra Operator Description Example Result + Addition x=2 4 y=2 x+y - Subtraction x=5 3 y=2 x-y * Multiplication x=5 20 y=4 x*y / Division 15/5 3 5/2 2,5 % Modulus (division remainder) 5%2 1 10%8 2 10%2 0 ++ Increment x=5 x=6 x++ -- Decrement x=5 x=4 x--
  • 22. Assignment Operators U-4 Javascript - Prof. D. P. Mishra Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y %= x%=y x=x%y
  • 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.
  • 29. JavaScript Basic Examples <script> document.write("Hello World!") </script>  format text with HTML code - heading <script> alert("Hello World!") </script> U-4 Javascript - Prof. D. P. Mishra
  • 30. Example <script> x=“Hello World!” document.write(x) </script> <script> x=“ BIT STUDENT.” document.write(“HELLO” +x) </script>  use line break html code U-4 Javascript - Prof. D. P. Mishra
  • 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
  • 34. Prompt Box Example <script> x=prompt (“Enter Your Name”, “ ”) document.write(“Hello <br>”,+x) </script> 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
  • 38. Examples -2 <script> s1=12 s2=28 total=s1+s2 document.write(“Total : "+total); </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>"); }
  • 43. U-4 Javascript - Prof. D. P. Mishra if…else Selection Statement (1) • Indicate different actions to be perform when condition is true or false grade >= 60 true print “Failed” false print “Passed”
  • 44. U-4 Javascript - Prof. D. P. Mishra if…else Selection Statement (2) • JavaScript Format: if ( boolean expression ) statement; else statement; • JavaScript Example : if ( grade >= 60 ) document.writeln(“Passed”); else document.writeln(“Failed”);
  • 45. U-4 Javascript - Prof. D. P. Mishra if…else Selection Statement (3) • Multiple actions • JavaScript Format : if ( boolean expression ) { statementOne; statementTwo; : }else { statementThree; statementFour; : }
  • 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
  • 47. U-4 Javascript - Prof. D. P. Mishra while Repetition Statement (1) • Repetition structure (loop)  Repeat action while some condition remains true. Product < = 1000 product = 2 * product true false
  • 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
  • 69. Objects Date Object GetDate() GetTime() GetDay() GetMonth() Math Object abs(number) log(number) random() String Object fontcolor() fontsize() ToLowerCase() ToUpperCase() Window Object alert(“message”) confirm(“message”) close() JavaScript enabled browsers have built-in objects which have properties, events and methods which can be used by JavaScript. For example: 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
  • 84. AJAX
  • 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
  • 87. AJAX Interaction Provides Validation Logic 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
  • 105. CSS
  • 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