You are on page 1of 56

Scripts vs.

Programs
a scripting language is a simple, interpreted
programming language

scripts are embedded as plain text, interpreted by


application

simpler execution model: don't need compiler or


development environment

platform-independence: code interpreted by any


script-enabled browser

but: slower than compiled code, not as powerful/full-


featured
JavaScript
Client side
Client: In a browser, JavaScript embedded
in html web pages

Relation to Java
Similar in syntax

JavaScript is case sensitive


E.g., null is not the same as Null,
NULL, or any other variant.
JavaScript: the first Web scripting language, developed by
Netscape in 1995 syntactic similarities to Java/C++, but
simpler, more flexible in some respects, limited in others
(loose typing, dynamic variables, simple objects)

JScript: Microsoft version of JavaScript, introduced in 1996


same core language, but some browser-specific
differences fortunately, IE, Netscape, Firefox, etc. can
(mostly) handle both JavaScript & JScript

JavaScript 1.5 & JScript 5.0 cores both conform to


ECMAScript standard

VBScript: client-side scripting version of Microsoft Visual


Basic
limitations of client-side scripting

since script code is embedded in the page, it is


viewable to the world

since they are designed to run on any machine


platform, scripts do not contain platform specific
commands

script languages are not full-featured


e.g., JavaScript objects are very crude, not good
for large project development
General Uses of JavaScript

Adds full programming language


features to web scripting
E.g., variables, iteration, functions

Dynamic creation of HTML code


HTML code can easily be output to the
browser
Dynamically interpreted by browser
Dynamic Typing & Operators
The type of a variable can be changed
e.g.,
var car = ford
car = 25
String concatenation: +
car = 2001 + toyota
Global Variable
Omitting a var declaration in an assignment creates a global varible
.e.g.,
x = 10 // x has not appeared before; x is global
Comments in JavaScript
// this is a comment

/* this starts a multiline comment*/

<!-- is a single line comment also- JavaScript does not recognize the
--> closing bracket
JavaScript
<html>
<head>
<title>JavaScript Page</title>
</head>

<body>
<script type="text/javascript">
// silly code to demonstrate output
document.write("<p>Hello world!</p>");
document.write("<p>How are <br/> " + "
<i>you</i>?</p> ");
</script>

<p>Here is some static text as well.</p>

</body>
</html>
JavaScript Data Types & Variables
<html>
<head>
<title>Data Types and Variables</title>
</head>
<body>
<script type="text/javascript">
var x, y;
x= 1024;
y= bias;
document.write("<p>x = " + x + "</p>");
document.write("<p>y = " + y + "</p>");
</script>
<</body>
/</html>

variables names are case-sensitive you don't have to declare variables, will be created the first time used, but its
better if you use var statements
var message, pi=3.14159; message = howdy;
JavaScript Data Types & Variables
<html>
<head>
<title>Data Types and Variables</title>
</head>
<body>
<script type="text/javascript">
var x,y,z;
x= 24;
y=100;
z=parseInt(x)+parseInt(y);
document.write("<B>Sum = " + z + "</B>");

</script>
<</body>
/</html>
Naming Form Elements in HTML

<form name="addressform">
Name: <input name="yourname"> <br>
Phone: <input name="phone"> <br>
Email: <input name="email"> <br>
</form>
Forms and JavaScript
document.formname.elementname.value
Thus:

document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value
JavaScript and HTML Forms

Interactive Programming on the Internet ,Knuckles


Naming Form Elements in HTML
<head><script>
function sum()
{ var x,y,z;
x=document.addressform.Subject1.value;
Y=document.addressform.Subject2.value;
z=parseInt(x)+parseInt(y);
document.addressform.Sum.value=z;
document.write("<B>Sum = " + z +
"</B>");
}</script> </head>
<Body><form name="addressform">
Subject1: <input name=Suject1>
<br>
Subject2: <input
name=Subject2><br>
Sum: <input name=Sum">
Naming Form Elements in HTML
<head><script>
function sum(f)
{ var x,y,z;
x=f.subject1.value;
Y=f.subject2.value;
z=parseInt(x)+parseInt(y);
f.Sum.value=z;
document.write("<B>Sum = " + z +
"</B>");
}</script> </head>
<Body><form>
Subject1: <input name=Suject1>
<br>
Subject2: <input
name=Subject2><br>
Sum: <input name=Sum">
JavaScript objects and events

event-driven programming
onClick,
onChange,
onLoad/onUnload
onClick,
onMouseOver,
onMouseOut
Etc.
DOM Events
User-Initiated scroll
click select
dlbclick
keydown
blur
keyup focus
keypress reset
mouseover Submit
mouseout
mousedown
Browser-Initiated
mouseup load
mousemove unload
change error
resize
abort
Using Form Data
alert box

<form name="alertform">
Enter your name:
<input type="text" name=name">
<input type="button" value= "Go"
onClick="window.alert('Hello ' +
document.alertform.name.value);">
</form>
Interactive Pages Using Prompt
<html>
<head>
<title>Interactive page</title>
user interaction
</head>
<body>
can take
<script type="text/javascript"> place using
var userName = prompt("What is your name?", "");
var userAge = prompt("Your age?", ""); prompt
var userAge = parseFloat(userAge);
document.write("Hello " + userName + ".")
if (userAge < 18) if value is a
{
document.write( Do your parents know " number, must
use parseFloat
+"you are online?"); (or parseInt) to
}
else convert
{
document.write(" Welcome friend!");
}
</script>
<p>The rest of the page...</p>
</body>
</html>
Array and looping statement
<HTML>
<SCRIPT type=text/javascript>
var names=new Array(5);
var i=0;
do
{
names[i]=window.prompt(Enter next name);
}while(i<5)
document.write(Output<BR>);
for(i in names)
{
document.write(names[i]+<BR>);
}
</SCRIPT>
</HTML>
User-Defined Functions
function isPrime(n)
if the first use of a
{ if (n < 2) variable is preceded
{ return false; with var, then that
} variable is local to
the function
else if (n == 2)
{ return true; for modularity,
} should make all
variables in a
else function local
{ for (var i = 2; i <= Math.sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
}
Function Example
<html>
<head>
<title>Prime Tester</title>
<script type="text/javascript">
function isPrime(n)
{ // CODE AS SHOWN ON PREVIOUS SLIDE }
</script>
</head>
<body>
<script type="text/javascript">
testNum = parseFloat(prompt("Enter a positive integer", 99"));
if (isPrime(testNum))
{ document.write(testNum + " <b>is</b> a prime number."); }
else
{ document.write(testNum + " <b>is not</b> a prime number."); }
</script>
</body>
</html>
set_Time_Out Function
<HTML><HEAD>
<SCRIPT>
var C=0;
ID1=window.setTimeout(update,2000);
function update()
{
C++;
alert(The counter is at+C);
Window.status=The counter is at+C;
ID1=window.setTimeout(update,2000);
}
</SCRIPT>
</HEAD>
<HR>
<BODY>
<FORM NAME=Time>
<INPUT TYPE=button VALUE=STOP
onclick
=Window.clearTimeout(ID1);>
</FORM>
</BODY></HTML>
Using timeouts to update a page every
two seconds
<HTML>
<SCRIPT type=text/javascript>
var counter =0;
ID1 =window.setTimeout(update();,2000);
function update()
{ counter++;
window.status=The counter is at+counter;
document.form.input.value=the counter is now
at+counter;
ID1=window.setTimeout(Update();,2000);
}
</SCRIPT>
<BODY>
<HI>Time out Example </HI><HR>
<FORM NAME=form>
<INPUT TYPE=Text NAME=input SIZE=40><BR>
<INPUT TYPE=button VALUE =RESET
onclick=counter=0;><BR>
<INPUT TYPE=button VALUE=STOP
onClick=Window.clearTimeout(ID1);>
</form>
<html><body>
<script>
var page=prompt("Enter page value(next/previous)");
switch(page)
{ case "next" :window.location="next.htm";
break;
case "previous" :window.location="previous.htm";
break;
default : alert("Wrong choice");
}
</script>
</body></html>
The 2015 Top Ten Programming Languages
The 2015 Top Ten Programming Languages
The big fiveJava, C, Python, and C#remain on top.

The big mover is R, a statistical computing language


thats handy for analyzing and visualizing big data,
which comes in at sixth place.

Last year it was in ninth place, and its move reflects the
growing importance of big data to a number of fields.

Apples own language, Swift. The development of


Swift started in 2010. companies such as Getty Images,
Duolingo, LinkedIn, and American Airlines are all using
Swift. Along with the open-source success of Swift and
the rising job market

<html>
<head>
<script>
function open_win()
{
Window.open("http://www.w3schools.com");
}
</script>
</head>
<body>
<input type="button" value="Open Window"
onClick="open_win();">
</body>
</html>
JavaScript and HTML Forms
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript>
function plus()
{ <BODY BGCOLOR="#FFFFCC">
var n1; <P>
var n2; <FORM name=addmultiply>
n1=document.addmultiply.num1.value;
n2=document.addmultiply.num2.value; <P>Enter a number in each field:
<INPUT TYPE=text NAME=num1 VALUE=""
n1=parseFloat(n1); SIZE=5>
n2=parseFloat(n2); <INPUT TYPE=text NAME=num2 VALUE=""
SIZE=5> <BR>
<INPUT TYPE=button VALUE="+"
document.addmultiply.result.value=n1+n2; onClick="plus();">
} <INPUT TYPE=button VALUE="*"
function times() onClick="times();">
{ <BR>
var n1; <INPUT TYPE=reset VALUE="Reset Form">
var n2; <BR>
n1=document.addmultiply.num1.value; <TEXTAREA NAME=result ROWS=3 COLS=27>
n2=document.addmultiply.num2.value; </TEXTAREA>
n1=parseFloat(n1);
</FORM>
n2=parseFloat(n2); </BODY>
</HTML>
document.addmultiply.result.value=n1*n2;
} </SCRIPT> </HEAD>
JavaScript objects and events
event-driven programming
onClick,onChange, onLoad/onUnload
onClick, onMouseOver, onMouseOut
Etc.

predefined classes & objects


String, Array, Date etc.
JavaScript Objects
a String object encapsulates a sequence of characters,
enclosed in quotes
properties include
length : stores the number of characters in the string
methods include
charAt(index) : returns the character stored at the given index
(as in C++/Java, indices start at 0)
substring(start, end): returns the part of the string between the start
(inclusive) and end (exclusive) indices
toUpperCase() : returns copy of string with letters uppercase
toLowerCase() : returns copy of string with letters lowercase

to create a string, assign using new or (in this case) just make a direct
assignment (new is implicit)
word = new String("foo"); word = "foo";

properties/methods are called exactly as in C++/Java


word.length word.charAt(0)
JavaScript Arrays
to create an array, allocate space using new (or can assign directly)

items = new Array(10); // allocates space for 10 items

items = new Array(); // if no size given, will adjust dynamically

items = [0,0,0,0,0,0,0,0,0,0]; // can assign size & values []

to access an array element, use [] (as in C++/Java)

for (i = 0; i < 10; i++) {


items[i] = 0; // stores 0 at each index

the length property stores the number of items in the array

for (i = 0; i < items.length; i++) {


document.write(items[i] + "<br>"); // displays elements
}
Date class
the Date class can be used to access the date and time
constructors include:

today = new Date(); // sets to current date & time

newYear = new Date(2001,0,1); //sets to Jan 1, 2001 12:00AM

methods include:

newYear.getYear() can access individual components of a date


newYear.getMonth()
newYear.getDay()
newYear.getHours()
newYear.getMinutes()
newYear.getSeconds()
newYear.getMilliseconds()

newYear.toString() can convert date to printable String


Date example

<html>

<head>
<title>Time page</title>
</head> Here, set to the current date and
time using the default
<body>
Time when page was loaded: constructor
<script language="JavaScript">
now = new Date();
toString displays the full date
document.write(now.toString() + "<br><br>"); using month and day names

document.write(now.getHours() + ":" + using the get methods, can


now.getMinutes() + ":" +
now.getSeconds()); display desired components of
</script> the date/time
</body>

</html>
<html>
<head>
</head>
<body>
<script type=text/javascript>
setInterval(printTime(), 1000);
function printTime()
{
Var now=new Date();
Var hours=now.getHours();
Var mins=now.getMinutes();
Var secounds=now.getSecounds();

Document.write(hours+:+mins+:+secounds+<br/>);
setInterval(printTime(), 1000);
}
</script>
</body>
view page in browser

</html>
User defined New Window
onClick="window.open('examples/sample
.htm,'Sample', 'toolbar=no, width=190,
height=190, left=500, top=200,
status=no, scrollbars=no, resize=no');
where examples/sample.htm is the path to
the file that will appear in the new window.

"Sample" is the name argument for the new


window.
User defined New Window
<html>
<head>
<script language="JavaScript">
function display()
{
displaywin= Window.open( ,new, toolbar=no,
status=no, width=300,
height=200);
msg=<UL><B>
NAME:</B></UL>+document.form1.name.value+<BR>;
msg+=<UL><B> ADDRESS:</B></UL>+
document.form1.address.value
<BR>;
displaywin.document.write(msg);
}
</script>
</head>
<body>
<FORM NAME=form1>
<B>Name:</B><INPUT TYPE=TEXT LENGTH=20 NAME=name>
<B>Address:</B><INPUT TYPE=TEXT LENGTH=30
NAME=address>
<INPUT TYPE=BUTTON VALUE=Display in New Window
User Defined Window
<HTML>
<BODY> <HI> create a new window</HI>
<FORM NAME=winform>
<INPUT TYPE=button VALUE= open new
window
onClick=newwin=Window.open( ,
NewWin,
toolbar=no,status=no,width=100,height=100);

<INPUT TYPE=button VALUE=Close New


Window onClick = newwin.close();>

<INPUT TYPE=button VALUE=Close Main


Window onClick=Window.close();>
</FORM>
</BODY>
</HTML>
User Defined Window
<HTML>
<FORM NAME=form action=mailto: user@host.com type=text/plain>
<B> Name: <\b> <INPUT TYPE>=TEXT LENGTH=20
NAME=yourname>
<B> Adress:<\B> <INPUT TYPE=TEXT LENGTH=20
NAME=Adress>
<B> Phone:<\B> <INPUT TYPE=TEXT LENGTH=30
NAME=Phone >
<INPUT TYPE =SUBMIT VALUE= submit>
<\FORM>
<\HTML>

submit a button submit a button that tells the browser


to take action on the form (typically to send it to a server)
Image events
<html>
<body>
<a href="javascript:alert('Do NOT click on me!');">
<img src=amit.gif" alt=Amit"> </a>
<p><br>
<img src="click1.gif"
onmouseover="this.src='click2.gif'"
onmouseout="this.src='click1.gif'"
onclick="alert('Thank you')">
</body>
</html>
OnLoad & OnUnload
<html><head>
<script language="JavaScript">
function Hello()
{
userName=prompt("Welcome to my page. " +
"What is your name?","");
}
function Goodbye()
{
userName=alert("So long, " + userName +
" come back real soon.");
}
</script></head>
<body onLoad="Hello();" onUnload="Goodbye();">
Whatever text appears in the page.
</body></html>

the ONLOAD attribute of the BODY tag specifies JavaScript code that is automatically
executed when the page is loaded
the ONUNLOAD attribute similarly specifies JavaScript code that is automatically
executed when the browser leaves the page
<html> <head> </head> Class and Object
<body> <script type="text/javascript">
function Emp(emp_name,emp_age,emp_sal)
{
this.emp_name=emp_name;
this.emp_age=emp_age;
this.emp_sal=emp_sal;
}
arrobj = [];
var num= parseInt(prompt("Enter No. of records","***"));
alert("Num="+num);
for(i=0;i<num;i++)
{
arrobj[i]=new Emp((prompt("Enter the Name of Employee","****")),(prompt("Enter the
Age of Employee","****")),(prompt("Enter the Salary of
Employee","****")));
}
if(confirm("Do you want to Retrieve?"))
{
var ind=parseInt(prompt("Enter the Array Index to Retrieve the record","***"));
document.write("The Name is"+arrobj[ind].emp_name);
document.write("The Age is"+arrobj[ind].emp_age);
document.write("The Sal is"+arrobj[ind].emp_sal);
}
else
{
alert("The Program is Over");
}
</script> </body> </html>
The Math Object & Math Methods
The syntax for applying a Math method is: value = Math.method(variable);
For example, AbsValue = Math.abs(NumVar);

48
Math Class Methods

JavaScript, Third Edition 49


Math Class Methods (Cont.)

JavaScript, Third Edition 50


Array Class Methods

JavaScript, Third Edition 51


JavaScript Allows Interactivity
Improve appearance
Especially graphics
Visual feedback

Site navigation

Perform calculations

Validation of input

Other technologies
JavaScript and HTML Forms

Form for submitting info for server side processing

Interactive Programming on the


Internet ,Knuckles
Mouse Event with map
<HTML>
<SCRIPT>
Function update(text value=text;
{
Document.forml.text/value=text;
}
<\SCRIPT>
<BODY>
<MAP NAME=mapl>
<AREA SHAPE= RECT COORDS=14,15,151,87
HREF=javascript:update(service);
On MouseOver=Window.statu=please select item,return
time;>
<AREA SHAPE=default HREF=javascript:update(No. item
selecte);
onMouseOver=Window.sttus=please select item,return
true;)
<\MAP>
<IMG SRC=image map.gif USE MAP=#map>
<FORM NAME=FORM>
<B> clicked item:</B>
<INPUT TYPE =text NAME= text VALUE= please select
an item>
<\FORM>
Mouse events with image
<html>
<body>
<SCRIPT TYPE=text/javascript>
<H1> An Example of Rollovers</H1>
<onMouseOver=document.images[0].src=
cloud.gif;
onMouseOut=document.images[0].src=
sky.gif;>
< IMG src=sky.gif width="192"

height="47 border=0>
</SCRIPT>
</BODY>
</html>
Ajax
Ajax allows a JavaScript procedure to
execute an HTTP transaction in the
background

Ajax can be used to fetch information,


images, etc., or to pass information to
the server in order to enhance the user
experience of a web page

You might also like