JavaScript
-
Upload
gisela-deleon -
Category
Documents
-
view
20 -
download
0
description
Transcript of JavaScript
JavaScript
JavaScript Basics It is a Scripting Language invented by Netscape in
1995. It is a client side scripting language.
Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side (on the web server). This type of computer programming is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be scripted; that is, to have different and changing content depending on user input, environmental conditions (such as the time of day), or other variables
2
3
Understanding Javascript
Javascript is used in million of web pages to
Improve design Validate forms Detect browsers Create cookies, etc.
Javascript is designed to add interactivity to HTML pages.
Advantages of Javascript An Interpreted language Embedded within HTML Minimal Syntax Quick Development Designed for Simple, Small programs Performance Procedural capabilities Handling User events Easy Debugging and Testing Platform Independent
4
5
JavaScript Basics
Prerequisites for learning javascript. Knowledge of basic HTML. You need a web browser. You need a editor. No need of special h/w or s/w or a web server.
6
Understanding Javascript
Javascript is used in million of web pages to
Improve design Validate forms Detect browsers Create cookies, etc.
Javascript is designed to add interactivity to HTML pages.
7
Understanding Javascript
Javascript is a scripting language developed by Netscape.
We can use nodepad, dreamweaver, golive .etc. for developing javascripts.
8
HTML and Javascript
The easiest way to test a javascript program is by putting it inside an HTML page and loading it in a javascript enabled browser.
You can integrate javascript code into the HTML file in three ways
Integrating under <head> tag Integrating under <body> tag Importing the external javascript.
9
HTML and Javascript
Integrating script under the <head> tag Javascript in the head section will execute
when called i.e javascript in the HTML file will execute immediately while the web page loads into the web browser before anyone uses it.
10
HTML and Javascript
Integrating script under the <head> tag Syntax :- <html>
<head> <script type=“text/javascript” > ----------------- </script> </head> <body> </body> <html>
11
HTML and Javascript
Integrating script under the <body> tag When you place the javascript code under
the <body> tag, this generates the content of the web page. Javascript code executes when the web page loads and so in the body section.
12
HTML and Javascript
Integrating script under the <body> tag Syntax :- <html>
<head></head>
<body><script type=“text/javascript” >
----------------- </script> </body> <html>
13
HTML and Javascript
Importing the External javascript You can import an external javascript file when
you want to run the same javascript file on several HTML files without having to write the same javascript code on every HTML file.
Save the external javascript file with an extension .js
The external javascript file don’t have a <script> tag.
14
HTML and Javascript
Importing the external javascript Syntax :- <html>
<head><script src=“first.js” >
----------------- </script>
</head> <body>
</body> <html>
15
First javascript program
The javascript code uses <script> </script> to start and end code.
The javascript code bounded with the script tags is not HTML to be displayed but rather script code to be processed.
Javascript is not the only scripting laguage, so you need to tell the browser which scripting language you are using so it knows how to process that language, so you specify <script type =“text/javascript”>
16
First javascript program
Including type attribute is a good practice but browsers like firefox, IE, etc. use javascript as their default script language, so if we don’t specify type attribute it assumes that the scripting language is javascript.
However use of type attribute is specified as mandatory by W3C.
17
First javascript program
<html><head> <title> first javascript </title>
</head>
<body><script type=“text/javascript” >
document.write(“First javascript stmt.”); </script>
</body> <html>
18
Elements of javascript
Javascript statement Every statement must end with a enter
key or a semicolon. Example :-
<script type=“text/javascript” >document.write(“First javascript
stmt.”);
</script>
19
Elements of javascript
Javascript statement blocks Several javascript statement grouped
together in a statement block. Its purpose is to execute sequence of
statements together. Statement block begins and ends with
a curly brackets.
20
Elements of javascript
Example :-<script type=“text/javascript” >
{
document.write(“First javascript stmt.”);
document.write(“Second javascript stmt.”);
}
</script>
21
Elements of javascript
Javascript comments It supports both single line and multi
line comments. // - Single line comments /*---------*/ - Multi line comments
22
Elements of javascript
Example :-<script type=“text/javascript” > // javascript
code{
/* This code will write two statement in the single line. */
document.write(“First javascript stmt.”); document.write(“Second javascript stmt.”);
} </script>
23
Variables
Basic syntax of variable declaration Syntax:- var variablename;
Naming conventions Variable name can start with a alphabet or underscore.
( Rest characters can be number, alphabets, dollar symbol, underscore )
Do not user any special character other than dollar sign ($), underscore (_)
Variable names are case-sensitive. Cannot contain blank spaces. Cannot contain any reserved word.
24
Variables
Once you declare a variable you can initialise the variable by assigning value to it. Syntax:- variablename=value;
You can also declare and initialize the variable at the same time. Syntax:- var variablename=value;
25
Variables
<html><head> <title> javascript variables </title> </head><body>
<script type=“text/javascript”> var bookname=“web tech and applications”;
var bookprice=390; document.write(“bookname is: ”,bookname);
document.write(“bookprice is: ”,bookprice);</script>
</body></html>
26
Datatypes
Javascript supports three primitive types of values and supports complex types such as arrays and objects. Number :consists of integer and floating
point numbers. Interger literals can be represented in decimal,
hexadecimal and octal form. Floating literal consists of either a number
containg a decimal point or an integer followed by an exponent.
27
Datatypes
Boolean :consists of logical values true and false. Javascript automatically converts
logical values true and false to 1 and 0 when they are used in numeric expressions.
28
Datatypes
String :consists of string values enclosed in single or double quotes.
Examples:
var first_name=“Bhoomi”;
var last_name=“Trivedi”;
var phone=4123778;
var bookprice=450.40;
29
Operators Arithmetic operators
Operator Action
+ Adds two numbers together
- Subtracts one number from another or changes a number to its negative
* Multiplies two numbers together
/ Divides one number by another
% Produces the remainder after dividing one number by another
30
Operators Addition
JavaScript can add together two or more numeric variables and/or numeric constants by combining them in an arithmetic expression with the arithmetic operator for addition ( + ).
The result derived from evaluating an expression can be assigned to a variable for temporary memory storage.
The following statements declare variables A and B and assign them numeric values; variable Sum is declared for storing the result of evaluating the arithmetic expression that adds these two variables.
Example :- var A = 20;var B = 10;var Sum = A + B;var Sum1 = 1 + 2;var Sum2 = A + 2 + B + 1;var Sum3 = Sum1 + Sum2;
31
Operators Other Arithmetic Operators
Operator Action
++ X++The equivalent of X = X + 1; add 1 to X, replacing the value of X
-- X--The equivalent of X = X - 1; subtract 1 from X, replacing the value of X
+= X += YThe equivalent of X = X + Y; add Y to X, replacing the value of X
-= X -= YThe equivalent of X = X - Y; subtract Y from X, replacing the value of X
*= X *= YThe equivalent of X = X * Y; multiply Y by X, replacing the value of X
/= X /= YThe equivalent of X = X / Y; divide X by Y, replacing the value of X
32
Operators Relational Operators
ConditionalOperator
Comparison
== Equal operator.value1 == value2Tests whether value1 is the same as value2.
!= Not Equal operator.value1 != value2Tests whether value1 is different from value2.
< Less Than operator.value1 < value2Tests whether value1 is less than value2.
> Greater Than operator.value1 > value2Tests whether value1 is greater than value2.
<= Less Than or Equal To operator.value1 <= value2Tests whether value1 is less than or equal to value2.
>= Greater Than or Equal To operator.value1 >= value2Tests whether value1 is greater than or equal to value2.
33
Operators Logical Operators
LogicalOperator
Comparison
&& And operator.condition1 && condition2The condition1 and condition2 tests both must be true for the expression to be evaluated as true.
|| Or operator.condition1 || condition2Either the condition1 or condition2 test must be true for the expression to be evaluated as true.
! Not operator.! conditionThe expression result is set to its opposite; a true condition is set to false and a false condition is set to true.
34
If condition Syntax:-
if (conditional expression)
{ do this... }
35
If – else condition Syntax:-
if (conditional expression)
{ do this... }
else
{ do this... }
36
Nested if condition Syntax:-
if (conditional expression) { if (conditional expression) { do this... } else { do this... } } else { if (conditional expression) { do this... } else { do this... } }
37
If..else if condition Syntax:-
if (conditional expression1) { do this... } else if (conditional expression2) { do this... } else if (conditional expression3) { do this... } ... [else {do this...}]
38
The Switch Statement Syntax:-
switch (expression)
{
case "value1": do this...
break
case "value2": do this...
break
...
[ default: do this... ]
}
39
Iterations For statement:-
for (exp1;exp2;exp3)
{
do this...
}
exp1:initial expression
exp2:conditional expression
exp3:incremental expression
40
Iterations while statement:-
while (conditional expression)
{
do this...
}
41
Iterations do …. while statement
do
{
do this...
}while (conditional expression)
42
Array Array is a javascript object that is capable of
storing a sequence of values. Array declaration syntax :
arrayname = new Array(); arrayname = new Array(arraylength);
In the first syntax an of size zero is created. In the second syntax size is explicitly specified,
hence this array will hold a pre-determined set of values.
43
Array Example :- bookname = new Array(); Note :- Even if array is initially created of a fixed
length it may still be extended by referencing elements that are outside the current size of the array.
Example :- cust_order = new Array();
cust_order[50] = “Mobile”;
cust_order[100] = “Laptop”;
44
Array Dense Array
It is an array that has been created with each of its elements being assigned a specific value.
They are declared and initialized at the same time.
Syntax:- arrayname = new Array(value0,value1,……..
…,valuen); Example :-
45
Array Array is a javascript object so it has several
methods associated with it. join() – it returns all elements of the array
joined together as a single string. By default “,” is used as a separator or you can specify the character to separate the array elements.
reverse() – it reverses the order of the elements in the array.
46
Array Array is a javascript object so it has also properties
associated with it. length - it determines the total number of
elements. Example :- length = myarray.length;
Javascript values for array could me of any type Example :- myarr = new Array(“one”,”two”,1,2, true, new Array(3,4) );
47
Special Operators Strict Equal (= = =)
Example “5” == 5 – true but “5” === 5 false It do not perform type conversion before testing for
equality. Ternary operators (? :)
Example :- condition ? Exp1 : Exp2 Delete operator
It is used to delete a property of an object or an element at an array index.
Example :- delete arrayname[5]
48
Special Operators New operator
It is used to create an instance of object type. Example :- myarr = new Array();
Void operator It does not return a value It is specially used to return a URL with no value.
49
Functions Functions are blocks of JS code that perform a
specific task and often return a value. Functions can be
Built in functions User defined functions
Built in functions Examples :
eval() parseInt() parseFloat()
50
Functions eval
It is used to convert a string expression to a numeric value. Example :- var g_total = eval (“10 * 10 + 5”);
parseInt It is used to convert a string value to an integer. It returns the first integer contained in a string or “0” if the
string does not begin with an integer. Example :-
var str2no = parseInt(“123xyz”); //123
var str2no =parseInt(“xyz”); //NaN
51
Functions parseFloat
It returns the first floating point number contained in a string or “0” if the string does not begin woth a valid floating point number.
Example :-
var str2no = parseFloat(“1.2xyz”); //1.2
52
Functions User Defined functions
When defining user defined functions appropriate syntax needs to be followed for Declaring functions Invoking / calling functions Passing values Returning and accepting the return values
53
Functions Function Declaration
Functions are declared and created using the function keyword.
A function can comprise of the following things, function name List of parameters Block of javascript code that defines what the function
does. Syntax :-
function function_name( P1, P2,………..,Pn)
{// Block of JS code
}
54
Functions Place of declaration
Functions can be declared any where within an HTML file.
Preferably functions are created within the <head> tags.
This ensures that all functions will be parsed before they are invoked or called.
55
Functions If the function is called before it is declared and
parsed, it will lead to an error condition as the function has not been evaluated and the browser does not know that it exists.
Parsed:- it refers to the process by which the JS interpreter evaluates each line of script code and converts it into a pseudo – compiled byte code before attempting to execute it.
At this time syntax errors and other programming mistakes that would prevent the script from running are trapped and reported.
56
Functions Function call
A variable or a static value can be passed to a function.
Example:-printName(“Bhoomi”);
var firstname=“Bhoomi”;
printName(firstname);
57
Functions Variable Scope
Any variable declared within the function is local to the function. Any variable declared outside the function is available to all the
statements within the JS code. Return Values
Use return statement to return a value or expression that evaluates to a single value.function cube(n){
var ans = n * n * n;return ans;
}
58
Functions Recursive Functions
A function calls itself. Example :-
function factorial( n){
if ( n >1 )return n * factorial( n-
1);else
return n;}
59
Dialog Boxes Dialog Boxes
JS provides the ability to pickup user input, display text to user by using dialog boxes.
These dialog boxes appear as separate windows and their content depends on the information provided by the user.
These content is independent of the text in the HTML page containing the JS code and does not affect the content of the page in any way.
There are three types of dialog boxes provided by JS, Alert dialog box Prompt dialog box Confirm dialog box
60
Dialog Boxes Alert dialog box
It is used to display small amount of “textual output” to a browser window.
The alert DB displays the string passed to the alert() as well as an OK button.
It is used to display a “cautionary message” or “some information” for eg Display message when incorrect information is keyed in a
form. Display an invalid result as an output of a calculation. A warning that a service is not available on a given date/time.
61
Dialog Boxes Syntax :- alert (“message”); Example :-<html>
<body><script type=“text/javascript”> alert(“This is a alert dialog box”);
document.write(“Hello”);</script>
</ body ></html>
62
63
Dialog Boxes Prompt Dialog Box Alert DB simply displays information in the
browser and does not allow any interaction. It halts program execution until some action
takes place. (i.e. click OK button) But it cannot be used to take input from user
and display output based on it. For this we use prompt DB.
64
Dialog Boxes Prompt Dialog Box Prompt() display the following things
A predefined message. A textbox ( with a optional value) A OK and CANCEL button.
It also causes program execution to halt until action takes place. (i.e OK or CANCEL ) Clicking OK causes the text typed inside the textbox to
be passed to the program environment. Clicking CANCEL causes a Null value to be passed to
the environment.
65
Dialog Boxes Prompt Dialog Box Syntax :- prompt( “msg”,”<default value>”); Example :-
<html><body>
<script type=“text/javascript”> var name;
name=prompt(“Enter you Name: ”,” “ “);document.write(“<br/>Name entered is : ”,name);
</script></ body >
</html>
66
67
Dialog Boxes Confirm Dialog Box Confirm() display the following things
A predefined message. A OK and CANCEL button.
It also causes program execution to halt until action takes place. (i.e OK or CANCEL ) Clicking OK causes true to be passed to the program,
which called Confirm DB. Clicking CANCEL causes false to be passed to the
program which called Confirm DB.
68
Dialog Boxes Confirm Dialog Box Syntax :- confirm( “message”); Example :-
<html><body>
<script type=“text/javascript”> var ans;
ans=confirm(“Are you sure want to exit ? “);if ( ans == true )
document.write(“ you pressed OK”);else
document.write(“ you pressed CANCEL”);
</script></ body >
</html>
69
70
71
Events Events
Event Handler Event
onclick The mouse button is clicked and released with the cursor positioned over a page element.
ondblclick The mouse button is double-clicked with the cursor positioned over a page element.
onmousedown The mouse button is pressed down with the cursor positioned over a page element.
onmousemove The mouse cursor is moved across the screen.
onmouseout The mouse cursor is moved off a page element.
onmouseover The mouse cursor is moved on top of a page element.
onmouseup The mouse button is released with the cursor positioned over a page element.