SlideShare uma empresa Scribd logo
1 de 40
Baixar para ler offline
JavaScript language
            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
                                             Microsoft- JScript IE 3
renamed as JavaScript1.1)


                  1997 ECMA (European
                  Computer Manufacturers
                  Association)
 Opera
                  Standardized ECMA script
 supporting
 JavaScript 1.1

            W3C standardized DOM to access HTML and XML
            JavaScript 1.2
Servlet files

                                              JSP files


   HTML file                                  HTML files
    JAVA
    SCRIPT
         Request


                              Response



Client                                    Web Server



             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>
                                document.write(“Hello”)
<HEAD>
<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
Function with return values
                              • Function
• Creation
                                 <html><head>
<html>
                                 <script language=“JavaScript”>
<head>
                                 <!--
<script language=“JavaScript”>
                                 function isNumber(x){
<!--
                                 for(i=0;i<x.length;i++){
function display(x){
                                 if(x.charAt(i)<‘0’ || x.charAt(i)>’9’)
document.write(x)}
                                 return false
-->
                                 }
</script>
                                 return true }
</head>
                                 -->
<body>
                                 </script></head><body>
<script>
                                 <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.
windowdocument  link
             history      anchor
             location     image
             frames       formbutton, 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 with user
<html><head>
<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=quot;open('win2.html','x' ,'menubar=0')quot;>
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,

Opening a new page on top window
location
<html><head>
</head>
<body>
<form>
<input type=button onCLick=“location.href=‘x.html’”>
</form>
</body>
</html>
Properties:
href, port,path, pathname
<html><head>
<title>Shop with us</title>
<script>
function display(x){
switch(x){
case 'left':
                     parent.b.l.location.href=quot;img.jpgquot;
                     break
case 'right':
                     parent.b.frames[1].location.href=quot;img.jpgquot;
                     break
case 'top':
                     top.location.href=quot;img.jpgquot;
                     break
case 'bottom' :
                     parent.b.location.href=quot;img.jpgquot;
                     break
case 'self' :
                     location.href=quot;img.jpgquot;
                     break


default:
           location.href=history.back()
}}
<body>


<form>
<input type=quot;buttonquot; value=quot;Leftquot;    onClick=quot;display('left')quot;>
<input type=quot;buttonquot; value=quot;Rightquot; onClick=quot;display('right')quot;>
<input type=quot;buttonquot; value=quot;Topquot;    onClick=quot;display('top')quot;>
<input type=quot;buttonquot; value=quot;Bottomquot;    onClick=quot;display('bottom')quot;>
<input type=quot;buttonquot; value=quot;selfquot;    onClick=quot;display('self')quot;>
<input type=quot;buttonquot; value=quot;backquot;    onClick=quot;display('xx')quot;>
</form>
</body>


</html>
document
Properties: images[], forms[], links[], anchors[],bgColor, fgColor,
title, linkColor, alinkColor, vlinkColor
Methods: open([mimetype]), write(expr1), close()


Example 1:bgColor and fgColor
<body onFocus=“bgColor=‘white’;fgColor=‘black’”
onBlur=“bgColor=‘black’;fgColor=‘black’”>
Example 2:Generating a document
<html><head><script>
function generate(){
win=open(quot;quot;,quot;genquot;)
win.document.open(quot;texthtmlquot;)
win.document.write(quot;<html><body onLoad=alert('ok')><U>Welcome</U>quot;)
win.document.write(quot;</body></html>quot;)
win.document.close() }
</script>
<body><form><input type=‘button’ onClick=‘generate()’></form></body>
</html>
images
Properties:border, height, width, src, name, complete
Creating new Image object:
im=new Image()
im=new Image(40,50)
Events:
onLoad, onError, onAbort, onMouseOver, onMouseOut, onDblClick
Example 1:
<html><head>
<script>
i=0
imgs=new
Array(quot;image1.jpgquot;,quot;image2.jpgquot;,quot;image3.jpgquot;,quot;image4.jpgquot;,quot;image5.jpgquot;)
function change(){
document.images[0].src=imgs[i++ % imgs.length]}
</script></head>
<body><img src=quot;image5.jpgquot; onMouseOver=quot;change()quot;>
</body>
On the internet it takes time to download the image. So to check if the
image has been downloaded and do the required we need image as object.
<script>
i=0
imgs=new Array(5)
for(i=0;i<5;i++){
imgs[i]=new Image()
imgs[i].src=quot;imagequot;+ (i+1)+quot;.jpg“ }
i=0
function set(){         setTimeout('change()',1000)   }
function change(){
if(imgs[i].complete){
document.images[0].src=imgs[i++ % imgs.length].src
set()}}
</script>
</head>
<body><img src=quot;image5.jpgquot;>
<script>set()</script></body></html>
form
Properties: action, method, name, elements[], target
Events: onSubmit, onReset
Form elements:
Events:All form elements: onBlur, onFocus
Select,text, textarea: onChange
Text, texrarea: onSelect
Button,submit,reset,radio,checkbox: onClick
Button: onMouseDown, onMouseUp,
TextArea: onKeyDown, onKeyUp, onKeyPress
Properties:
All : name, type, value (except select)
radio, checkbox: checked, defaultChecked
select: length, options[], selectedIndex
text, password, textarea:defaultValue
 Methods:
All form elements: focus(), blur()
button,submit, reset: click()
Example 1: Working with text, radio and checkbox
<html><head><title>Validate</title><script>
<!--
function check(){
 with(document.forms[0]){
 if ((name.value==quot;quot;) ){
       alert(quot;Please ensure that all fields are filled upquot;)
       return false   }
if(like[0].checked)
s= quot;Thankyou, quot;+name.value +quot;.quot;
else
s=quot;Sorry !quot;
s=s+quot; As per your suggestion   we shall look into areas:(quot;;
for(i=0;i<better.length;i++)
 if (better[i].checked)
  s=s+ better[i].value+quot;,quot;
       s=s+quot; and more ) for further improvements quot; }
alert(s)
//-->
</script>
</head><body>
<form   action=quot;Frame.htmlquot; onSubmit=quot;return check()quot;>
Name: <input type=text name=name><br><br>
Do you like our site
<input type=radio name=quot;likequot;   checked>Yes
<input type=radio name=quot;likequot; >No<br><br>
Tell us how we can make this site better for you:<br>
<input type=checkbox name=quot;betterquot; value=quot;Change bgcolorquot;>Change the bg
color<br>
<input type=checkbox name=quot;betterquot; value=quot;Change fgcolorquot;>Change the fg
color<br>
<input type=checkbox name=quot;betterquot; value=quot;Change layoutquot;>Change the
layout<br>
<input type=checkbox name=quot;betterquot; value=quot;More servicesquot;>Include more
services<br><br>
<input type=submit></form>
</body>
</html>
Example 2: Working with select
<html><head><script>
<!--
function check(){
 i=document.f1.choose.options.selectedIndex;
if(i!=0){ if(i==1)
alert(quot;Correctquot;);
else
alert(quot;Your choice, quot;+ document.f1.choose.options[i].text +quot;- is
incorrectquot;);
}}
//-->
</script></head>
<body>
<form name=f1>
Which of the following is not true about JavaScript?
<select name=quot;choosequot; onChange=quot;check()quot;>
<option>-------Select the best answer--------</option>
<option>JavaScript is object-oriented language</option>
<option>JavaScript is loosely typed language</option>
<option>JavaScript is used for client side validations</option>
<option>JavaScript is platform independent</option>
</select>


</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.
Date object
var dt= new Date();
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()+quot;:quot;+dt.getMinutes()+quot;:quot;+dt.getSeconds();
document.forms[0].time.value=str;
timer=setTimeout(quot;setTime()quot;,1000);
}
</script>
</head>
<body><form>
<input type=text name=quot;timequot; 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

Mais conteúdo relacionado

Mais procurados (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScript
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Jsp
JspJsp
Jsp
 
Rich faces
Rich facesRich faces
Rich faces
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Javascript
JavascriptJavascript
Javascript
 
Seam Glassfish Slidecast
Seam Glassfish SlidecastSeam Glassfish Slidecast
Seam Glassfish Slidecast
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server Pages
 

Destaque

Jfa (1983) criteria for determining attribute man made lithics patterson
Jfa (1983) criteria for determining attribute man made lithics  pattersonJfa (1983) criteria for determining attribute man made lithics  patterson
Jfa (1983) criteria for determining attribute man made lithics pattersonJulio Cesar Sierra
 
Aanti (1987) formation of flakes cotterell y kamminga
Aanti (1987) formation of flakes  cotterell y kammingaAanti (1987) formation of flakes  cotterell y kamminga
Aanti (1987) formation of flakes cotterell y kammingaJulio Cesar Sierra
 
Mainstream Green The 9 Rules By North 1231227359000658 1
Mainstream Green The 9 Rules By North 1231227359000658 1Mainstream Green The 9 Rules By North 1231227359000658 1
Mainstream Green The 9 Rules By North 1231227359000658 1gueste76bac7
 
Ims Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüS
Ims Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüSIms Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüS
Ims Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüSzewe
 
Jen Pepper studio work
Jen Pepper studio workJen Pepper studio work
Jen Pepper studio workJenPepper
 
How To Crash The Party North 1231226907563744 1
How To Crash The Party North 1231226907563744 1How To Crash The Party North 1231226907563744 1
How To Crash The Party North 1231226907563744 1gueste76bac7
 
Venture 360 Report Overview For Entrepreneurs 1232000447204805 2
Venture 360 Report Overview For Entrepreneurs 1232000447204805 2Venture 360 Report Overview For Entrepreneurs 1232000447204805 2
Venture 360 Report Overview For Entrepreneurs 1232000447204805 2gueste76bac7
 
Oracle Course
Oracle CourseOracle Course
Oracle Courserspaike
 
My Bio Homework
My Bio HomeworkMy Bio Homework
My Bio Homeworketnies576
 
Lablogs no ScienceOnline'09
Lablogs no ScienceOnline'09Lablogs no ScienceOnline'09
Lablogs no ScienceOnline'09carloshotta
 
Presentasi Bisnis Investasi Auworldwide
Presentasi Bisnis Investasi AuworldwidePresentasi Bisnis Investasi Auworldwide
Presentasi Bisnis Investasi Auworldwideprieku
 
Mlm Business Start Up Power Point
Mlm Business Start Up   Power PointMlm Business Start Up   Power Point
Mlm Business Start Up Power PointRich Price
 

Destaque (16)

Qualified Plan Overview for Advisors
Qualified Plan Overview for AdvisorsQualified Plan Overview for Advisors
Qualified Plan Overview for Advisors
 
Jfa (1983) criteria for determining attribute man made lithics patterson
Jfa (1983) criteria for determining attribute man made lithics  pattersonJfa (1983) criteria for determining attribute man made lithics  patterson
Jfa (1983) criteria for determining attribute man made lithics patterson
 
Aanti (1987) formation of flakes cotterell y kamminga
Aanti (1987) formation of flakes  cotterell y kammingaAanti (1987) formation of flakes  cotterell y kamminga
Aanti (1987) formation of flakes cotterell y kamminga
 
Mainstream Green The 9 Rules By North 1231227359000658 1
Mainstream Green The 9 Rules By North 1231227359000658 1Mainstream Green The 9 Rules By North 1231227359000658 1
Mainstream Green The 9 Rules By North 1231227359000658 1
 
Ims Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüS
Ims Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüSIms Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüS
Ims Learner Information Package Spetsifikatsiooni Tugi Erinevates õPihaldussüS
 
Alm caiib
Alm  caiibAlm  caiib
Alm caiib
 
Jen Pepper studio work
Jen Pepper studio workJen Pepper studio work
Jen Pepper studio work
 
How To Crash The Party North 1231226907563744 1
How To Crash The Party North 1231226907563744 1How To Crash The Party North 1231226907563744 1
How To Crash The Party North 1231226907563744 1
 
Abg ship
Abg shipAbg ship
Abg ship
 
Venture 360 Report Overview For Entrepreneurs 1232000447204805 2
Venture 360 Report Overview For Entrepreneurs 1232000447204805 2Venture 360 Report Overview For Entrepreneurs 1232000447204805 2
Venture 360 Report Overview For Entrepreneurs 1232000447204805 2
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
 
My Bio Homework
My Bio HomeworkMy Bio Homework
My Bio Homework
 
Lablogs no ScienceOnline'09
Lablogs no ScienceOnline'09Lablogs no ScienceOnline'09
Lablogs no ScienceOnline'09
 
00b7d51a6233d925e2000000
00b7d51a6233d925e200000000b7d51a6233d925e2000000
00b7d51a6233d925e2000000
 
Presentasi Bisnis Investasi Auworldwide
Presentasi Bisnis Investasi AuworldwidePresentasi Bisnis Investasi Auworldwide
Presentasi Bisnis Investasi Auworldwide
 
Mlm Business Start Up Power Point
Mlm Business Start Up   Power PointMlm Business Start Up   Power Point
Mlm Business Start Up Power Point
 

Semelhante a Jscript Fundamentals

Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005Tugdual Grall
 
Introduction of javascript
Introduction of javascriptIntroduction of javascript
Introduction of javascriptsyeda zoya mehdi
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java scriptnanjil1984
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)Carles Farré
 
Introduction to javaScript
Introduction to javaScriptIntroduction to javaScript
Introduction to javaScriptNeil Ghosh
 
Lecture 5 - Comm Lab: Web @ ITP
Lecture 5 - Comm Lab: Web @ ITPLecture 5 - Comm Lab: Web @ ITP
Lecture 5 - Comm Lab: Web @ ITPyucefmerhi
 
Real-World AJAX with ASP.NET
Real-World AJAX with ASP.NETReal-World AJAX with ASP.NET
Real-World AJAX with ASP.NETgoodfriday
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentalsRajiv Gupta
 
Internet Technology and its Applications
Internet Technology and its ApplicationsInternet Technology and its Applications
Internet Technology and its Applicationsamichoksi
 

Semelhante a Jscript Fundamentals (20)

Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Introduction of javascript
Introduction of javascriptIntroduction of javascript
Introduction of javascript
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
I Feel Pretty
I Feel PrettyI Feel Pretty
I Feel Pretty
 
Tugas Pw [6]
Tugas Pw [6]Tugas Pw [6]
Tugas Pw [6]
 
Tugas Pw [6] (2)
Tugas Pw [6] (2)Tugas Pw [6] (2)
Tugas Pw [6] (2)
 
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
[DSBW Spring 2009] Unit 07: WebApp Design Patterns & Frameworks (3/3)
 
GWT
GWTGWT
GWT
 
Introduction to javaScript
Introduction to javaScriptIntroduction to javaScript
Introduction to javaScript
 
JavaScripts & jQuery
JavaScripts & jQueryJavaScripts & jQuery
JavaScripts & jQuery
 
Lecture 5 - Comm Lab: Web @ ITP
Lecture 5 - Comm Lab: Web @ ITPLecture 5 - Comm Lab: Web @ ITP
Lecture 5 - Comm Lab: Web @ ITP
 
Real-World AJAX with ASP.NET
Real-World AJAX with ASP.NETReal-World AJAX with ASP.NET
Real-World AJAX with ASP.NET
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentals
 
Internet Technology and its Applications
Internet Technology and its ApplicationsInternet Technology and its Applications
Internet Technology and its Applications
 
Ajax
AjaxAjax
Ajax
 

Último

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 

Jscript Fundamentals

  • 1. JavaScript language 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
  • 2. 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 Microsoft- JScript IE 3 renamed as JavaScript1.1) 1997 ECMA (European Computer Manufacturers Association) Opera Standardized ECMA script supporting JavaScript 1.1 W3C standardized DOM to access HTML and XML JavaScript 1.2
  • 3. Servlet files JSP files HTML file HTML files JAVA SCRIPT Request Response Client Web Server Script Programs executes executes on the locally and server and sends interacts with the response
  • 4. 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
  • 5. 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>
  • 6. External Script JSfile.js <HTML> document.write(“Hello”) <HEAD> <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>
  • 7. Nuts and Bolts Learning Objectives Variables and datatypes Conversion Operators Control statements Arrays Functions
  • 8. 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>
  • 9. 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
  • 10. 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>
  • 11. 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
  • 12. Function with return values • Function • Creation <html><head> <html> <script language=“JavaScript”> <head> <!-- <script language=“JavaScript”> function isNumber(x){ <!-- for(i=0;i<x.length;i++){ function display(x){ if(x.charAt(i)<‘0’ || x.charAt(i)>’9’) document.write(x)} return false --> } </script> return true } </head> --> <body> </script></head><body> <script> <script> <!— <!— display(“hello”) if(isNumber(“123”) --> document.write(“number”) </script> else </body> document.write(“not a number”) </html> --></script></body></html>
  • 13. •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>
  • 14. •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>
  • 15. 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
  • 16. 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. windowdocument  link history anchor location image frames formbutton, text, password,radio, checkbox, select submit, reset, hidden Array, String, Date, Math
  • 17. 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=
  • 18. Communicating with user <html><head> <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>
  • 19. 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>
  • 21. open() <html> <head> <title>win4</title> </head> <body onLoad=quot;open('win2.html','x' ,'menubar=0')quot;> 1. HTTP is a ______________ protocol<br> a) application layer<br> b) session layer<br> c) transport layer<br> d) network layer </body> </html>
  • 22. location, frames, history, Opening a new page on top window
  • 24. <html><head> <title>Shop with us</title> <script> function display(x){ switch(x){ case 'left': parent.b.l.location.href=quot;img.jpgquot; break case 'right': parent.b.frames[1].location.href=quot;img.jpgquot; break case 'top': top.location.href=quot;img.jpgquot; break case 'bottom' : parent.b.location.href=quot;img.jpgquot; break case 'self' : location.href=quot;img.jpgquot; break default: location.href=history.back() }}
  • 25. <body> <form> <input type=quot;buttonquot; value=quot;Leftquot; onClick=quot;display('left')quot;> <input type=quot;buttonquot; value=quot;Rightquot; onClick=quot;display('right')quot;> <input type=quot;buttonquot; value=quot;Topquot; onClick=quot;display('top')quot;> <input type=quot;buttonquot; value=quot;Bottomquot; onClick=quot;display('bottom')quot;> <input type=quot;buttonquot; value=quot;selfquot; onClick=quot;display('self')quot;> <input type=quot;buttonquot; value=quot;backquot; onClick=quot;display('xx')quot;> </form> </body> </html>
  • 26. document Properties: images[], forms[], links[], anchors[],bgColor, fgColor, title, linkColor, alinkColor, vlinkColor Methods: open([mimetype]), write(expr1), close() Example 1:bgColor and fgColor <body onFocus=“bgColor=‘white’;fgColor=‘black’” onBlur=“bgColor=‘black’;fgColor=‘black’”> Example 2:Generating a document <html><head><script> function generate(){ win=open(quot;quot;,quot;genquot;) win.document.open(quot;texthtmlquot;) win.document.write(quot;<html><body onLoad=alert('ok')><U>Welcome</U>quot;) win.document.write(quot;</body></html>quot;) win.document.close() } </script> <body><form><input type=‘button’ onClick=‘generate()’></form></body> </html>
  • 27. images Properties:border, height, width, src, name, complete Creating new Image object: im=new Image() im=new Image(40,50) Events: onLoad, onError, onAbort, onMouseOver, onMouseOut, onDblClick Example 1: <html><head> <script> i=0 imgs=new Array(quot;image1.jpgquot;,quot;image2.jpgquot;,quot;image3.jpgquot;,quot;image4.jpgquot;,quot;image5.jpgquot;) function change(){ document.images[0].src=imgs[i++ % imgs.length]} </script></head> <body><img src=quot;image5.jpgquot; onMouseOver=quot;change()quot;> </body>
  • 28. On the internet it takes time to download the image. So to check if the image has been downloaded and do the required we need image as object. <script> i=0 imgs=new Array(5) for(i=0;i<5;i++){ imgs[i]=new Image() imgs[i].src=quot;imagequot;+ (i+1)+quot;.jpg“ } i=0 function set(){ setTimeout('change()',1000) } function change(){ if(imgs[i].complete){ document.images[0].src=imgs[i++ % imgs.length].src set()}} </script> </head> <body><img src=quot;image5.jpgquot;> <script>set()</script></body></html>
  • 29. form Properties: action, method, name, elements[], target Events: onSubmit, onReset Form elements: Events:All form elements: onBlur, onFocus Select,text, textarea: onChange Text, texrarea: onSelect Button,submit,reset,radio,checkbox: onClick Button: onMouseDown, onMouseUp, TextArea: onKeyDown, onKeyUp, onKeyPress Properties: All : name, type, value (except select) radio, checkbox: checked, defaultChecked select: length, options[], selectedIndex text, password, textarea:defaultValue Methods: All form elements: focus(), blur() button,submit, reset: click()
  • 30. Example 1: Working with text, radio and checkbox <html><head><title>Validate</title><script> <!-- function check(){ with(document.forms[0]){ if ((name.value==quot;quot;) ){ alert(quot;Please ensure that all fields are filled upquot;) return false } if(like[0].checked) s= quot;Thankyou, quot;+name.value +quot;.quot; else s=quot;Sorry !quot; s=s+quot; As per your suggestion we shall look into areas:(quot;; for(i=0;i<better.length;i++) if (better[i].checked) s=s+ better[i].value+quot;,quot; s=s+quot; and more ) for further improvements quot; } alert(s)
  • 31. //--> </script> </head><body> <form action=quot;Frame.htmlquot; onSubmit=quot;return check()quot;> Name: <input type=text name=name><br><br> Do you like our site <input type=radio name=quot;likequot; checked>Yes <input type=radio name=quot;likequot; >No<br><br> Tell us how we can make this site better for you:<br> <input type=checkbox name=quot;betterquot; value=quot;Change bgcolorquot;>Change the bg color<br> <input type=checkbox name=quot;betterquot; value=quot;Change fgcolorquot;>Change the fg color<br> <input type=checkbox name=quot;betterquot; value=quot;Change layoutquot;>Change the layout<br> <input type=checkbox name=quot;betterquot; value=quot;More servicesquot;>Include more services<br><br> <input type=submit></form> </body> </html>
  • 32. Example 2: Working with select <html><head><script> <!-- function check(){ i=document.f1.choose.options.selectedIndex; if(i!=0){ if(i==1) alert(quot;Correctquot;); else alert(quot;Your choice, quot;+ document.f1.choose.options[i].text +quot;- is incorrectquot;); }} //--> </script></head> <body> <form name=f1> Which of the following is not true about JavaScript? <select name=quot;choosequot; onChange=quot;check()quot;>
  • 33. <option>-------Select the best answer--------</option> <option>JavaScript is object-oriented language</option> <option>JavaScript is loosely typed language</option> <option>JavaScript is used for client side validations</option> <option>JavaScript is platform independent</option> </select> </form> </body> </html>
  • 34. 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”) }
  • 35. <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)
  • 36. 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.
  • 37. Date object var dt= new Date(); 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()+quot;:quot;+dt.getMinutes()+quot;:quot;+dt.getSeconds(); document.forms[0].time.value=str; timer=setTimeout(quot;setTime()quot;,1000); } </script>
  • 38. </head> <body><form> <input type=text name=quot;timequot; 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) }
  • 39. 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>
  • 40. 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