javascript
DESCRIPTION
JavaScript, Client Side Web TechnologyTRANSCRIPT
BCA (2012‐15)Client Side Web Technology
JavaScript Notes
1
What is JavaScript?
• Designed to add interactivity to HTML pages• Scripting language (Lightweight programming• language)• Embedded directly in HTML pages• Interpreted language• Open software (Free)• Supported by all major browsers, like• Netscape and Internet Explorer
2
Java and JavaScript
• Are Java and JavaScript the same?– NO!
• Java and JavaScript are two completelydifferent languages!
• Java (developed by Sun Microsystems)• is a powerful and very complex• programming language ‐ in the same• category as C and C++
3
JavaScript Capabilities
• Programming tool ‐ Scripting language with a verysimple syntax
• Dynamic text into an HTML page ‐ Example:document.write("<h1>" + name + "</h1>")
• Reacting to events ‐ Execute when somethinghappens, like when a page has finished loading or
• when a user clicks on an HTML element• Read and write HTML elements ‐ A JavaScript canread and change the content of an HTML element
• Validate data ‐ A JavaScript can be used to validateform data before it is submitted to a server, this willsave the server from extra processing
4
Simple Example
<html><body><script type="text/javascript">document.write("Hello World!")</script></body></html>
5
Example with a Header
<html><body><script type="text/javascript">JavaScript | Atul Kahate 6document.write("<h1>Hello World!</h1>")</script></body></html>
6
Where to Put JavaScript?
• Scripts in a page will be executedimmediately while the page loads intothe browser
• This is not always what we want• Sometimes we want to execute a scriptwhen a page loads, other times when auser triggers an event
7
Controlling When a JavaScriptShould Execute – 1
• Scripts in the head section– Scripts to be executed when they arecalled, or when an event is triggered, go inthe head section
• When we place a script in the headsection, we will ensure that the script isloaded before anyone uses it
8
Controlling When a JavaScriptShould Execute – 2
• Scripts in the body section– Scripts to be executed when the pageloads in the body section
–When we place a script in the body sectionit generates the content of the page
9
Controlling When a JavaScriptShould Execute – 3
• Scripts in the head and body sections– We can place an unlimited number of
scripts in our document, so we can havescripts in both the body and the headsection.
10
External JavaScript
<html><head></head><body><script src="xxx.js"></script></body></html>
11
Script in the head section<html><head><script type="text/javascript">function message(){alert("This alert box was called with the onload event")}</script></head><body onload="message()"></body></html>
12
Script in the Body Element<html><head></head><body><script type="text/javascript">window.document.write("This message is written when the page
loads")</script></body></html>
13
Declaring Variables in JavaScript
• You can declare a variable with the var statement: var strname = some value You can also declare a variable by simply assigning a value to the variable. But if you do not assign a value and simply use the variable then it leads to an error. Strname = some value
• You assign a value to a variable like this: • var strname = "Hello" Or like this:
• strname = "Hello"
14
Data Types in JavaScript1. Number
3 or 7.987 are the examples of Integer and floating‐point numbers.Integers can be positive, 0, or negative;Integers can be expressed in decimal (base 10), hexadecimal (base16), and octal (base 8).A decimal integer literal consists of a sequence of digits without aleading 0 (zero). A leading 0 (zero) on an integer literal indicates it is inoctal; a leading 0x (or 0X) indicates hexadecimal.Hexadecimal integers can include digits (0‐9) and the letters a‐f and A‐F. Octal integers can include only the digits 0‐7.A floating‐point number can contain either a decimal fraction, an "e"(uppercase or lowercase), that is used to represent "ten to the powerof" in scientific notation, or both.The exponent part is an "e" or "E" followed by an integer, which can besigned (preceded by "+" or "‐"). A floating‐point literal must have atleast one digit and either a decimal point or "e" (or "E"). 15
Continued….• Boolean True or False. The possible Boolean values are true and false.• String
"Hello World!” Strings are delineated by single or double quotation marks.
• Object MyObj = new Object()
• Null Not the same as zero – no value at all. A null value is one that has no value and means nothing.
• Undefined A value that is undefined is a value held by a variable after it has been created, but before a value has been assigned to it.
16
17
Adding Comments :Comments are useful for providing additional information for
debugging and remembering what you did
Single line comments ‐ (// )
// comment text
Multi‐line comments (/* */)
/* comments
More comments */
Hiding from older browsers
<script type=“text/javascript”>
<!‐‐ This will hide JavaScript from older browsers Script ‐‐>
</script>
18
Variables :The names of the variables and functions must follow these simplerules.
The first character must be a letter of the alphabet (lowercaseor uppercase), an underscore (_) or a dollar sign ($). The dollarsign is not recommended as it is not supported prior to JavaScriptver 1.1.You CANNOT use a number as the first character of the name.Names CANNOT contain spaces.Names CANNOT match any of the reserved words.
Examples of valid names:xadd_two_numx13_whatever$money_string
19
Reserved Words in JavaScriptThere are a number of words that make up the components of
the JavaScript language. These words cannot be used for variable or function names because the program interpreter would be unable to distinguish between a default JavaScript command and your variable or function name.Example:
while,catch,else,if,this,with,class,enum,import,throw,const,export,in,true,continue,extends,new,try,debugger,false,null,typeof,default ,finally,return,var,abstract ,delete ,innerWidth ,Packages ,status ,alert ,do ,instanceof ,pageXOffset ,statusbar ,break,for,super,void,case,function,switch,
20
Output Types in JavaScript
Alert Box: an alert box will display specified text in a box that contains an ok button.
Are generally used for warnings.
alert(“This is used to display the Answer!!!”);
Confirm box: an alert box that contains text – usually in the form of a question – and an OK and Cancel button.
confirm(“Type your question between the quotes –ok?”);
Prompt Box: an alert box that prompts the user
to input text.
Provide 2 pieces of information:
– Text to be displayed – usually a question
– Initial value of the text box
prompt(“What is your name”, ”Enter your name
here”);
prompt(“What is your favorite school?”, “SICSR”)
21
Operators :
Operators are used to handle variables.
Types of operators with examples:
Arithmetic operators, such as plus.
Comparisons operators, such as equals.
Logical operators, such as and.
Control operators, such as if.
Assignment and String operators
22
JavaScript Operators :
Arithmetic OperatorsEg. : + ‐ * / %Comparison OperatorsEg. : == != < > <= >=Logical OperatorsEg. : && || !Bitwise OperatorsEg. : & | ^ >> >>> <<Ternary OperatorsEg. : ?:
23
Arithmetic Operators :Operator Description Example Result
+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
5/2 2,5
% Modulus (division remainder) 5%2 1
10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
24
Assignment Operators :
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
25
Comparison Operators :
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
26
Logical Operators :Operator Description Example
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
27
Statements :expressionifswitchwhiledoforbreakcontinuereturntry/throw
28
Conditional Statements :
►Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:►if statement ‐ use this statement if you want to execute some code only if a specified condition is true ►if...else statement ‐ use this statement if you want to execute some code if the condition is true and another code if the condition is false ►if...else if....else statement ‐ use this statement if you want to select one of many blocks of code to be executed ►switch statement ‐ use this statement if you want to select one of many blocks of code to be executed .
29
Syntax :
if (condition){code to be executed if condition is true}
if (condition){ code to be executed if condition is true }else{ code to be executed if condition is not true }
Example : <script language=“Javascript”>x=3if(x<0){ alert (“negative”)}else{ alert (“positive”)}</script> 30
Switch Statement :•Multiway branch
•The switch value does not need to a number. It can be a string.
•The case values can be expressions.Syntax :switch (expression) {case ';':case ',':case '.':punctuation();break;
default:noneOfTheAbove( );
}31
Break & Continue Statement :
‐ Alter flow of controlbreak;
mExits structurecontinue;
mSkips remaining statements in structure; continues with next loop iterationWhen used properly
mPerforms faster than the corresponding structured techniques
32
Looping :Very often when you write code, you want the same block of
code to run a number of times. You can use looping statements in your code to do this.In JavaScript we have the following looping statements: while ‐ loops through a block of code while a condition is
true do...while ‐ loops through a block of code once, and then
repeats the loop while a condition is true for ‐ run statements a specified number of times
33
Syntax :
WhileSyntax: while (condition){code to be executed}
do...whileSyntax: do {code to be executed } while (condition)
ForSyntax: for (initialization; condition; increment) {code to be executed
}34
Example of for loop :
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
}
</script></body></html>
35
Example of do – while loop :
<html>
<body>
<script type="text/javascript">
i = 1
do
{ document.write("<h" + i + ">This is header " + i)
document.write("</h" + i + ">")
i++
}
while (i <= 6)
</script></body></html> 36
Functions In JavaScript :
Enables modularization
Makes code reusable
Reduce size and complexity of code
Efficiency by avoiding repetition
Limits details needed to be remembered
Ensures consistency
Modifications are only made once
37
Functions :
A module of code that performs a specific task
Types of functions
Pre‐defined in JavaScript
User‐defined
Functions may:
Accept data
Return a value
Do something else
Or any combination of the three38
Functions :
Define the functions in the <head> </head>
section of an HTML page inside <script> </script> tags.
Function names become reserved once used
We call functions within the <body> </body>
portion of an HTML page.
Functions are not executed until they are called in the </body> portion of an HTML page.
39
Functions :
When the browser encounters a call to a
function, it passes control to that function and
executes it.
When it finishes executing the function,
control is passed back to where the function
was called from and proceeds to whatever is
next.
40
Defining Functions :
function FunctionName (parameters)
{
Do something with arguments Define the function here…
return something; Optional
}
... ...and later we use it
variable = FunctionName (arguments);
41
Rules For Naming The Function :
The name of the function:
Must start with a letter or an underscore
Can contain letters, digits, and
underscores in any combination
Cannot contain space
Cannot contain special characters
42
Functions :
Parameters represent the inputs in the
function header
Data needed by the function
Arguments represent the inputs specified in
the function call
Data provided to the function
Arguments and parameters are mapped
according to their order
Needs to be a 1‐to‐1 mapping43
Return Values :
A function can return a value but it is not required
Return statements return a single value
The calling program must be set to accept that value either by assigning it to a variable, or having it part of output
Functions without a return statement have a
specific purpose that does not require a value
to be sent back to the calling program
Output
44
Example Of simple Function :
<html><head><script type="text/javascript">function myfunction(){alert("HELLO")}</script></head><body><form><input type="button" onclick="myfunction()" value="Call function"></form><p>By pressing the button, a function will be called. The function will alert a message.</p></body></html>
45
Event Handling In JavaScript
46
EventsEvents are actions that trigger when user does something.Every element on a web page has certain events which can trigger JavaScript functions.For ex.A form event is the clicking on a button. Events are objects with properties.
JavaScript defines five types of events which are form, image, image map, link, and window events. Events are associated with HTML tags. Examples of events:
•A mouse click •A web page or an image loading •Mousing over a hot spot on the web page •Selecting an input box in an HTML form •Submitting an HTML form •A keystroke
47
Form Events•blur ‐ The input focus was lost. •change ‐ An element lost the focus since it was changed. •focus ‐ The input focus was obtained. •reset ‐ The user reset the object, usually a form. •select ‐ Some text is selected •submit ‐ The user submitted an object, usually a form.
Image Eventsabort ‐ A user action caused an abort. •error ‐ An error occurred. •load ‐ The object was loaded.
Image Map Events•mouseOut ‐ The mouse is moved from on top a link. •mouseOver ‐ The mouse is moved over a link.
48
Link Events•click ‐ An object was clicked. •mouseOut ‐ The mouse is moved from on top a link. •mouseOver ‐ The mouse is moved over a link.
Window Events•blur ‐ The input focus was lost. •error ‐ An error occurred. •focus ‐ The input focus was obtained. •load ‐ The object was loaded. •unload ‐ The object was exited.
49
Meaning of Event :•abort ‐ A user action caused an abort of an image or document load. •blur ‐ A frame set, document, or form object such as a text field loses the focus for input. •click ‐ Happens when a link or image map is clicked on •change ‐ Happens when a form field is changed by the user and it loses the focus. •error ‐ An error happened loading a image or document. •focus ‐ A frame set, document, or form object such as a text field gets the focus for input. •load ‐ The event happens when an image or HTML page has completed the load process in the browser.•mouseOut ‐ The event happens when the mouse is moved from on top of a link or image map •mouseOver ‐ The event happens when the mouse is placed on a link or image map. •reset ‐ The user reset the object which is usually a form. •submit ‐ The user submitted an object which is usually a form. •unload ‐ The object such as a frameset or HTML document was exited by the user
50
Common Events for HTML TAGS :1) <A> •click (onClick) •mouseOver (onMouseOver) •mouseOut (onMouseOut) 2) <BODY> •blur (onBlur) •error (onError) •focus (onFocus) •load (onLoad) •unload (onUnload) 3) <FORM> •submit (onSubmit) •reset (onReset)4) <IMG> •abort (onAbort) •error (onError) •load (onLoad)
5 ) <FRAME>
•blur (onBlur)
•focus (onFocus)
6) <FRAMESET>
•blur (onBlur)
•error (onError)
•focus (onFocus)
•load (onLoad)
•unload (onUnload)
51
8) <INPUT TYPE = "button"> •click (onClick)
9) <INPUT TYPE = "checkbox"> •click (onClick)
10 ) <INPUT TYPE = "reset"> / <INPUT TYPE = "submit"> •click (onClick)
11) <INPUT TYPE = "text"> •blur (onBlur) •focus (onFocus) •change (onChange) •select (onSelect)
12) <SELECT> •blur (onBlur) •focus (onFocus) •change (onChange)
13) <TEXTAREA> •blur (onBlur) •focus (onFocus) •change (onChange) •select (onSelect)
52
Event Handlers :
Event handlers are created as follows:
onEvent = "Code to handle the event"
For Ex. Onload=add( )
53
onload and onUnload
The onload event is triggered when the user enters the page. The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
onUnload event is triggered when the user leaves the page.Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.
54
Example Of Event Handling :
<html>
<head> <script>
function myfunction()
{
alert("Welcome to my world!!");
}
</script></head>
<body>
<form name="myform">
<input type="button" value="click me" onclick="myfunction()">
</form>
</body>
</html> 55
OBJECTS IN JAVASCRIPT
56
Objects
57
– Attributes– Behaviors– Encapsulate date and methods– Property of information hiding– Details hidden within the objects themselves
Built In Objects JavaScript
58
Array <html><script>
a= Array(12,112,3)b=Array(11,a)
document.write(b.toString())document.write("<br>"+a[0] )document.write("<br>"+b.length + "<br>")c=b.concat(a)c=a.join('Hello')document.write("<br>"+c )document.write("<br>"+a.reverse() )document.write("<br>"+a.sort() )
</script></html>
59
String<html><script>
/********* String object (Methods , Properties )********/str="hello"document.write("<br>"+ str.big())document.write("<br>"+ str.blink())document.write("<br>"+ str.bold())document.write("<br>"+ str.charAt(4).bold())
document.write("<br>"+ str.charCodeAt(0))document.write("<br>"+ str.concat(" Everybody"))
document.write("<br>"+ str.fontcolor("blue").fontsize(40))
s=str.fromCharCode(34,7,7)
document.write("<br>"+ str.indexOf('l'))
CONTD.60
Continued…..document.write("<br>"+ str.lastIndexOf("l"))document.write("<br>"+ str.italics().bold())document.write("<br>"+ str.length)document.write("<br>"+ str.link("math.htm"))document.write("<br>"+ str.replace("ll","LL"))document.write("<br>"+ str.search("ll"))document.write("<br>"+ str.small())
document.write("<br>"+ str.slice(2))document.write("<br>"+ str.split("e"))document.write("<br>"+ str.strike())document.write("<br>"+ "Hi"+str.sub())document.write("<br>"+ "Hi"+str.sup())
document.write("<br>"+ str.substring(2))document.write("<br>"+ str.substring(1,2))document.write("<br>"+ str.toLowerCase())document.write("<br>"+ str.toUpperCase())document.write("<br>"+ String.toString(""))document.write("<br>"+ str.valueOf())
</script></html>
CONTD.
61
Date<html><script>
d=new Date()document.write(d.getDate()+"<br>")document.write(d.getHours()+"<br>")document.write(d.getTime()+"<br>")
/*******************************************//*d.setDate()d.setHours()d.setTime()*//******************************************/</script></html>
62
Math<script> document.writeln(Math.sin(90) + " <br>")document.writeln(Math.cos(90) + " <br>")document.writeln(Math.abs(‐90) + " <br>")document.writeln(Math.ceil(90.7878) + " <br>")document.writeln(Math.tan(90) + " <br>")document.writeln(Math.floor(90.235) + " <br>")document.writeln(Math.pow(2,3) + " <br>")document.writeln(Math.random() + " <br>")document.writeln(Math.sqrt(25) + " <br>")document.writeln(Math.asin(30 * 3.14/180) + " <br>")document.writeln(Math.acos(30 * 3.14/180) + " <br>")document.writeln(Math.atan(30 * 3.14/180) + " <br>")document.writeln(Math.exp(2) + " <br>")document.writeln(Math.log(2) + " <br>")document.writeln(Math.max(2,40) + " <br>")document.writeln(Math.min(2,40) + " <br>")</script>
63
64
Using Browser Objects
• In the previous lectures, you were introduced to predefined objects in JavaScript– Math, String, Object, Boolean, Date, …
• JavaScript also provides you with objects that can control and manipulate the displays of browsers.– More dynamic and interactive.
• When a browser loads a webpage, it creates a number of JavaScript objects.
Document Object Model (DOM)
65
• DOM is an object‐oriented model that describes how
all elements in an HTML page are arranged.
• It is used to locate any object in your HTML page (an
unique address).
66
How the DOM works?<head><script>function toggle() { document.img.button1.src=“button_on.gif”; }</script></head><body><a href=“test.html” onmouseover=“toggle()”> <img name=“button1” src=“button_off.gif”></a></body>
action
reaction
Action Event JavaScript DOM Reaction
src=“button_off.gif” onmouseover toggle() document.img.button1 Src=“button_on.gif”
1) User moves mouse over object2) Event senses that something happened to the object3) JavaScript tells the object what to do (Even handler)4) Locates object on the web page5) Object’s image source is changed
67
Browser Hierarchy Modelwindow
document frame location history
anchor image form link
button checkbox
select
textarea
submit
radio
reset
text
68
The “window” Object
• It is the highest‐level object in the JavaScript browser object hierarchy.
• It is the default object and is created automatically when a page is loaded.
• Since it is the default object, we may omit writing window explicitly.– document.write(“a test message”);– window.document.write(“a test message”);
• It also includes several properties and methods for us to manipulate the webpage.
69
Properties and methods of the “window” Object
Property Descriptionlength An integer value representing the number of frames in the
windowname A string value containing the name of a windowparent A string value containing the name of the parent windowstatus A string value representing status bar text
Method Descriptionalert(text) Pop up a window with “text” as the message
close() Closes the current windowopen(url) Open a new window populated by a URL.
setTimeout(expression, time) Executes an expression after the elapse of the interval time.
70
Example of using the “window” Object
• Opening and closing windows• Window attributes of the “open()”method
Attribute Description
toolbar Creates the standard toolbar
location Creates the location entry field
directories Creates standard directory buttons
status Creates the status bar
menubar Creates the menu bar at the top of a window
scrollbars Creates scrollbars when the document exceeds the window size
resizable Enables the user to resize the window
width Specifies the width of the window
height Specifies the height of the window
Opening New Window :
There’s a JS command to open a new browser window. The third parameter is opitonal, and covers stuff like size, whether it will have scrollers, etc.
window.open("URL","name","features");
Example : Open a new window when clicking on a button<html>
<head> <script language=javascript>
function openwindow()
{ window.open("http://google.com") }
</script></head>
<body><form>
<input type=button value="Open Window" onclick="openwindow()">
</form> </body></html>71
Example of Different Window.open Parameters and hyperlink:<html><head><script type="text/javascript">function openwindow(){window.open("http://sicsr.ac.in","window1","width=250,height=300")}</script></head><body><form><input type="button" value="Open Window" onclick="openwindow()"><P><A href="javascript: openwindow()">Open the JavaScript Window on hyperlink</A></P></form></body> </html>
72
Location :The Location object is part of a Window object and is accessed through the window.location property. It contains the complete URL of a given Window object, or, if none is specified, of the current Window object.
Example :<html><head><script type="text/javascript">function openwindow(){ window.location = "http://www.yahoo.com" }</script></head><body><form><input type="button" value="Open Window" onclick="openwindow()"><P><A href="javascript: openwindow()">Open the JavaScript Window on hyperlink</A></P></form></body> </html>
73
74
The “document” Object
• It is one of the important objects in any window or frame.
• The document object represents a web document or a page in a browser window.
• When you access multiple sites simultaneously, there would be multiple windows opened. – Each window would have a corresponding window object, and each window object would have its own document object.
INE2720 –Web Application Software Development All copyrights reserved by C.C. Cheung 2003. 75
Properties and methods of the “document” Object
Property DescriptionbgColor A string value representing the background color of a document
alinkColor A string value representing the color for active linkslocation A string value representing the current URL
title A string value representing the text specified by <title> tag
Method Descriptionclear() Clears the document window
write(content) Writes the text of content to a documentwriteln() Writes the text and followed by a carriage returnopen() Open a document to receive data from a write() streamclose() Closes a write() stream
76
The “form” Object
• The form object is accessed as a property of the document object.
• Each form element in a form (text input field, radio buttons), is further defined by other objects.
• The browser creates a unique “form” object for each form in a document.
• You can access the form object “form1”– document.form1
77
Form Element‐Based Objects
• HTML forms can include eight types of input elements– Text fields, Textarea fields– Radio buttons– Check box buttons– Hidden fields– Password fields– Combo box select menu– List select menu– Each object has its own properties and methods.