Академический Документы
Профессиональный Документы
Культура Документы
fundamentals
Learning Objectives
Brief history of JavaScript
Uses
Language features
Inclusion of script in HTML
<noscript> and hiding scripts
Scripts inside <body> and <head>
External scripts
Brief history of JavaScript
Netscape developed a scripting language called LiveScript
Supported both client side and server side scripting
Netscape Navigator 2
(support for java applets and LiveScript
renamed as JavaScript1.1) Microsoft- JScript IE 3
JSP files
Response
Script Programs
executes executes on the
locally and server and sends
interacts with the response
Uses
• To create more interactive pages- client side validations etc.
• To generate html dynamically.
• Event handling
• To enhance browser capabilities by giving it a better look – printing
on status bar etc.
• Interaction with embedded components like applets and active x
controls.
Language Features
• Object based language:no object inheritance and subclassing. Object
-based because it depends on built-in objects to function.
• Semicolon, as separator for multiple statements in the same line.
• Syntax similar to c++ and java
• Case sensitive
• Loosely typed
• Platform independent
• Interpreted
Scripts in HTML
<HTML><HEAD><TITLE>Hello</TITLE></HEAD>
<BODY>
First java script code<br>
<SCRIPT>
//Java script single line comment
document.write(“Hello java script”)
/* java script script
multi-line comment */
</SCRIPT></BODY></HTML>
NOSCRIPT and hiding scripts
Some browser don’t support javascript. They will display the javascript on the
web page since they cannot interpret. To avoid that the script need to be
commented. Also for such browsers <NOSCRIPT> tag may be used which
can display alternative text for scripts.
<SCRIPT>
<!—
document.write(“Hello java script”)
-->
</SCRIPT>
<NOSCRIPT>Java script is not supported</NOSCRIPT>
External Script
JSfile.js
<HTML>
<HEAD> document.write(“Hello”)
<BODY>
<SCRIPT LANGUAGE=“JavaScript”
SRC=“JSfile.js”>
</SCRIPT>
</BODY>
</HTML>
Scripts inside body and head
Inside head only declarations should be done. No write
statements must appear inside head tag.
<HTML><HEAD><TITLE>Hello</TITLE>
<SCRIPT>
document.write(“Hello java script”) Incorrect
</SCRIPT>
</HEAD>
<BODY></BODY>
Nuts and Bolts
Learning Objectives
Variables and datatypes
Conversion
Operators
Control statements
Arrays
Functions
Variables and Datatypes
• Variable names must begin with a letter, under-score or $.,
subsequent characters can be letter or number.
• Variables need not be declared in JavaScript. They just need to
be assigned with proper data. They are called data stores.
• Data types supported by Java Script are
d) Numeric – integer and floating point numbers (64 bit, IEE754
floating point)
e) Strings
f) Boolean- true, false
g) Null, Undefined and NaN
<HTML><HEAD><SCRIPT LANGUAGE=“JavaScript” >
$I=“hello”
</SCRIPT></HEAD>
<BODY><SCRIPT LANGUAGE=“JavaScript”>
document.write($I)
</script>
</body>
Conversion: parseInt() and parseFloat()
Operators
Arithmetic: + - * / % += -= *= /= %=
Logical: & | ! && ||
Relational: > >= < <= == !=
String concatenation: +
Bit wise: >> << >>> >>= <<= >>>=
Mixing up datatypes:
S=“abc”
I=123
document.write(S+I) abc123
S=“abc”
B=true
document.write(S+B) abctrue
B=true
I=123
document.write(B+1) 124
Control statements
• Same as in c++ or java
• if else
• for
• while
• do .. while
• switch
<HTML><HEAD><SCRIPT LANGUAGE=“JavaScript” >
</SCRIPT></HEAD>
<BODY><SCRIPT LANGUAGE=“JavaScript”>
i=15
b=true
for(j=2;j<=i/2;j++){
if(i%j==0){
b=false;
break;}
}
if(b) document.write(i + “ is a prime number”)
else document.write(i + “ is not a prime number”)</script>
</body></html>
•
Arrays
Declaration: are objects in JavaScript
a= new Array(3)
a[0]=1 a[1]=2 a[2]=3
• A single array can hold any kind of data
junk= new Array(3)
junk[0]=“Sunday” junk[1]=0 junk[2]=true
• Array length
a.length
• Array size is incremented dynamically
a= new Array()
a[4]=4
a.length is 5
• Initialized array
week=new Array(“sun”,”mon”,”tue”,”wed”,”thu”,”fri”,”sat”)
document.write(week[0]) sun
document.write(week) sun, mon, tue, wed …
• Array of array: matrix= new Array(new Array(1,2,3), new Array(4,5,6)
a[0][1] 2
• Creation
Function
• Function with return values
<html> <html><head>
<head> <script language=“JavaScript”>
<script language=“JavaScript”> <!--
<!-- function isNumber(x){
function display(x){ for(i=0;i<x.length;i++){
document.write(x)} if(x.charAt(i)<‘0’ || x.charAt(i)>’9’)
--> return false
</script> }
</head> return true }
<body> -->
<script> </script></head><body>
<!— <script>
display(“hello”) <!—
--> if(isNumber(“123”)
document.write(“number”)
</script>
else
</body>
document.write(“not a number”)
</html>
--></script></body></html>
•Calling a function
function display(x){
if(x==null)
x=“Greetings”
document.write(x) }
Can be called as : display() or display(“hello”)
No overloading possible. If overloaded functions are provided, only the last
function is considered
•Function arguments: arguments array can be used to collect the arguments
of a function.
<script language=“JavaScript”>
<!--
function sum(){
total=0
for(j=0;j<sum.arguments.length;j++){
total+=sum.arguments[j];
document.write(sum)}
--></script>
•Local and Global variables
Local variables are created using var
<!--
function sum(){
total=0 var total=0 then it is available only in the function
for(j=0;j<sum.arguments.length;j++){
total+=sum.arguments[j];
}
--></script>
…
<script>
<!—
document.write(total) // ok doesn't display if local variable
-->
</script>
JavaScript Object Model,
window object
Learning Objectives
Object Model
window object
properties
methods
events
Example communicating with the user
Example displaying status bar messages on window events
Example working with timer
JavaScript Object Model
• Also called DOM (document object model) or web
browser object model.
• JavaScript interacts with the web browser using the
objects defined in the Object model.
windowdocument link
history anchor
location image
frames formbutton, text,
password,radio,
checkbox, select
submit, reset, hidden
Array, String, Date, Math
window object
•window is the default object that is available to the JavaScript.
•document.write document is an object inside window and instead
of document.write we can also write window.document.write implying
write on current window’s document.
•Properties:
name, self, top, parent, opener, defaultStatus, status, closed, length
Methods: alert(displayString), String prompt(question,defaultanswer),
boolean confirm(question), Timer setTimeOut(expression, millsecs),
clearTimeOut(timerobj), blur(), focus(), open(url,name,[options]),
close()
Events: onLoad, onUnload, onFocus, onBlur, OnError
[options]: menubar=,toolbar,status, width=, height=
Communicating
<html><head>
with user
<script>
function communicate(){
alert(“Hello”)
s=prompt(“What is your name”, “xyz”)
b=confirm(“Do you want to see your name displayed in colors”)
a=new Array(“RED”,”GREEN”,”BLUE”,”YELLOW”, “BLACK”,”PURPLE)
while(b){
document.write(“<font color=“+a[i]+”>”+s+”</font>”)
if(i++>a.length)i=0
b=confirm(“Do you want to continue”)}}
</script>
</head><body onUnload=“alert(‘Bye!’)”>
<script> communicate()</script>
</body></html>
status bar and window events
<html><head>
<script>
function setStatus(x){
status=x
}
</script>
</head>
<body onLoad=“defaultStatus=‘welcome’”
onBlur=“setStatus(‘OUT’) onFocus=“setStatus(“ON”)>
Look at the status bar
</body>
</html>
Timer
<html><head>
<script>
a=new Array(“Welcome”,”to”,”jis”)
i=0
function setTimer(){
setTimeout(“display()”,1000);
}
function display(){
status=a[i]
i=i++%3
setTimer()
}
open()
<html>
<head>
<title>win4</title>
</head>
<body onLoad="open('win2.html','x' ,'menubar=0')">
1. HTTP is a ______________ protocol<br>
a) application layer<br>
b) session layer<br>
c) transport layer<br>
d) network layer
</body>
</html>
location, frames, history,
default:
location.href=history.back()
}}
<body>
<form>
<input type="button" value="Left" onClick="display('left')">
<input type="button" value="Right" onClick="display('right')">
<input type="button" value="Top" onClick="display('top')">
<input type="button" value="Bottom" onClick="display('bottom')">
<input type="button" value="self" onClick="display('self')">
<input type="button" value="back" onClick="display('xx')">
</form>
</body>
</html>
document
Properties: images[], forms[], links[], anchors[],bgColor, fgColor,
title, linkColor, alinkColor, vlinkColor
Methods: open([mimetype]), write(expr1), close()
</form>
</body>
</html>
link, anchor and history
links, anchors: array
properties: href, hostname, pathname, port, target, protocol
Events: onClick, onDblClick, onKeyDown, onKeyUp, onKeyPress,
onMouseDown, onMouseUp, onMouseOver, onMouseOut
Example: Game
<html><head>
<script>
arr=new Array(‘one.hif’,’two.gif’)
i=0
im=“”
function f(x){
r=Math.floor(Math.random()*2)
document.images[x].src=arr[r]
if(i==0) im=arr[r]
if(i++>0 && im==arr[r])
alert(“You have won in “+ i + “ attempts”)
}
<body>
<table><tr>
<td><a href=“#” onClick=f(1)><img src=“blank.gif”></a></td>
<td><a href=“#” onClick=f(2)><img src=“blank.gif”></a></td></tr>
<td><a href=“#” onClick=f(3)><img src=“blank.gif”></a></td>
<td><a href=“#” onClick=f(4)><img src=“blank.gif”></a></td></tr>
</table>
</body>
</html>
History
Property: length
Methods:
back()
forward()
go(x)
Math
Properties: PI, E
Methods: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x),
round(x), floor(x), ceil(x), max(x,y), min(x,y), sqrt(x), pow(x,y),
random(), log(x)
Rounding:
with(Math){
X=floor(3.5) 3
Y=ceil(3.5)4
Z=round(3.5) 4
}
r=Math.floor(Math.random()*2)
r between 0 and 1.
var dt= new Date();
Date object
Creates a new date object which contains system’s current date and
time.
Methods:
getDate() getMonth() getYear()
getHours() getMinutes() getSeconds()
setDate(value) setMonth(value)
setYear(value) setHours(value)
setMinutes(value) setSeconds(value)
toGMTString() toLocalString()
Example 1:
<html><head><title>time</title><script>
<!--
function setTime()
{
dt= new Date();
str=dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds();
document.forms[0].time.value=str;
timer=setTimeout("setTime()",1000);
}
</script>
</head>
<body><form>
<input type=text name="time" readonly size=6>
</form>
<script>setTime()</script>
</body></html>
Example 2:
Difference between two dates:
<script>
Function diff(){
dt1=new Date();
dt2=new Date(2005,8,5)
millsec=1000*60*60*24
Days=Math.round((dt1-dt2)/millsec)
alert(“no of days “+ days)
}
String object
Method Example HTML
anchor(aname) “Part2”.anchor(“p2”) <a name=“p2”>Part2</a>
big() “Welcome”.big() <BIG>Welcome</BIG>
blink() “Highlights”.blink() <BLINK>Highlights</BLINK>
bold() “Hello”.bold() <B>Hello</B>
italics() “sky”.italics() <I>Sky</I>
link(url) Yahoo.link( <a href=www.yahoo.com>
www.yahoo.com) Yahoo</a>
small() “Rights <small>Rights
reserved”.small() reserver</small>
strike() “strike”.strike() <strike>strike</strike>
sub() “h”+”2”.sub()+ “o” h <SUB>2</SUB>o
sup() “E=MC”+”2”.sup() E=MC<SUP>2</SUP>
Methods Examples Results
toLowerCase() “Hi”.toLowerCase() hi
toUpperCase() “hi”.toUpperCase() HI
length “hi”.length 2
indexOf(searchText, “hello.indexOf(“e”,0) 1
startposition)
substring(startpos, “hello”.substring(1,3) el
endpos)
charAt(indexPos) “hello”.charAt(4) O