0% found this document useful (0 votes)
6 views

Lecture 6

This is Lecture note-2

Uploaded by

Kirubel
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture 6

This is Lecture note-2

Uploaded by

Kirubel
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

Introduction to JavaScript

Introduction

• What is it?
• How does it work?
• What is Java?
• Learning JavaScript
• JavaScript Statements
• JavaScript and HTML forms
What is JavaScript?

• Browsers have limited functionality


• Text, images, tables, frames
• JavaScript allows for interactivity
• Browser/page manipulation
• Reacting to user actions
• A type of programming language
• Easy to learn
• Developed by Netscape
• Now a standard exists –
www.ecma-international.org/publications/
standards/ECMA-262.HTM
JavaScript Allows Interactivity

• Improve appearance
• Especially graphics
• Visual feedback
• Site navigation
• Perform calculations
• Validation of input
• Other technologies
How Does It Work?

• Embedded within HTML page


• View source
• Executes on client
• Fast, no connection needed once loaded
• Simple programming statements combined with HTML tags
• Interpreted (not compiled)
• No special tools required
What is Java?

• Totally different
• A full programming language
• Much harder!
• A compiled language
• Independent of the web
• Sometimes used together
Learning JavaScript

• Special syntax to learn


• Learn the basics and then use other people's
(lots of free sites)
• Write it in a text editor, view results in browser
• You need to revise your HTML
• You need patience and good eyesight!
The document.write() and document.writeIn()
Methods

• to display the text “Only 45 days until Christmas” in a Web page:


document.write (“Only 45 days until
Christmas”);
• an object (the page that the Web browser is accessing)
• action that can be applied to the document
• The term “method” means an action applied to
something existing on a Web page or in the Web
browser.
JavaScript Objects

Object JavaScript
Object Name
The browser window window
A frame within the browser window frame
History list containing the Web page history
The browser being run by the user navigator
The URL of the current web page location
Web page shown in browser window document
A form on the current Web page form
DOM (Document Object Model)
JavaScript Statements

<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">

document.write('This is my first 
JavaScript Page');
Note the symbol for
</script> line continuation
</body>
</html>
JavaScript Statements

<html>
<head><title>My Page</title></head>
<body>
<script language=“JavaScript">

document.write('<h1>This is my first 
JavaScript Page</h1>');
HTML written
</script> inside JavaScript
</body>
</html>
JavaScript Statements
<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseover="window.alert('Hello');">
My Page</A>
</p>
</body> An Event JavaScript written
</html> inside HTML
Example Statements

<script language="JavaScript">
window.prompt('Enter your name:','');
Another event
</script>

<form>
<input type="button" Value="Press"
onClick="window.alert('Hello');">
</form>
Note quotes: " and '
HTML Forms and JavaScript

• JavaScript is very good at processing user input in the web browser


• HTML <form> elements receive input
• Forms and form elements have unique names
• Each unique element can be identified
• Uses JavaScript Document Object Model (DOM)
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
Using Form Data

Personalising an alert box

<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' + 
document.alertform.yourname.value);">
</form>
Language Elements

• Variables
• Literals
• Operators
• Control Structures
• Objects

19
JavaScript Variables

• Untyped!
• Can be declared with var keyword:
var foo;

• Can be created automatically by assigning a value:


foo=1; blah="Hi Dave";

20
Variables (cont.)

• Using var to declare a variable results in a local variable (inside a


function).

• If you don't use var – the variable is a global variable.

21
Literals

• The typical bunch:


• Numbers 17 123.45
• Strings "Hello Dave"
• Boolean: true false
• Arrays: [1,"Hi Dave",17.234]

Arrays can hold anything!

22
Operators

• Arithmetic, comparison, assignment, bitwise, boolean (pretty much just


like C).

+ - * / % ++ -- == != > <
&& || ! & | << >>

23
Control Structures
• Again – pretty much just like C:
if if-else ?: switch

for while do-while

• And a few not in C


for (var in object)

with (object)

24
Objects

• Objects have attributes and methods.


• Many pre-defined objects and object types.
• Using objects follows the syntax of C++/Java:
objectname.attributename
objectname.methodname()

25
Array Objects

• Arrays are supported as objects.

• Attribute length

• Methods include:
concat join pop push reverse sort

26
Array example code

var a = [8,7,6,5];

for (i=0;i<a.length;i++)
a[i] += 2;

b = a.reverse();

27
Many other pre-defined object types

• String: manipulation methods


• Math: trig, log, random numbers
• Date: date conversions
• RegExp: regular expressions
• Number: limits, conversion to string

28
Predefined Objects

• JavaScript also includes some objects that are automatically created for
you (always available).
• document
• navigator
• screen
• window

29
The document object

• Many attributes of the current document are available via the


document object:
Title Referrer
URL Images
Forms Links
Colors

30
document methods

• document.write() like a print statement – the output goes into


the HTML document.

document.write("My title is" + document.title);

string concatenation!

31
JavaScript Example
<HEAD>
<HEAD>
<TITLE>JavaScript
<TITLE>JavaScript isis Javalicious</TITLE>
Javalicious</TITLE>
</HEAD>
</HEAD>
<BODY>
<BODY>
<H3>I
<H3>I am
am aa web
web page
page and
and here
here is
is my
my
name:</H3>
name:</H3>
<SCRIPT>
<SCRIPT>
document.write(document.title);
document.write(document.title);
</SCRIPT>
</SCRIPT>
<HR>
<HR>

32
JavaScript and
HTML Comments
<SCRIPT> t
en
<!-- m
om
document.write("Hi Dave"); c
L
document.bgColor="BLUE"; T M
-->
H
</SCRIPT>

33
JavaScript Functions

• The keyword function used to define a function


(subroutine):

function add(x,y) {
return(x+y);
}

34
JavaScript Events

• JavaScript supports an event handling system.


• You can tell the browser to execute javascript commands when some event
occurs.
• Sometimes the resulting value of the command determines the browser action.

35
Simple Event Example
<BODY
<BODY BGCOLOR=WHITE
BGCOLOR=WHITE onUnload="restore()">
onUnload="restore()">
<H5>Hello
<H5>Hello -- II am
am aa very
very small
small page!</H5>
page!</H5>
<SCRIPT>
<SCRIPT>
savewidth
savewidth == window.innerWidth;
window.innerWidth;
saveheight
saveheight == window.innerHeight;
window.innerHeight;
function
function restore()
restore() {{
window.innerWidth=savewidth;
window.innerWidth=savewidth;
window.innerHeight=saveheight;
window.innerHeight=saveheight;
}}
//
// Change
Change the
the window
window size
size to
to be
be small
small
window.innerWidth=300;
window.innerWidth=300; window.innerHeight=50;
window.innerHeight=50;
document.bgColor='cyan';
document.bgColor='cyan';
</SCRIPT>
</SCRIPT>

36
Buttons
• You can associate buttons with JavaScript events (buttons in HTML
forms)

<FORM>
<FORM>
<INPUT
<INPUT TYPE=BUTTON
TYPE=BUTTON
VALUE="Don't
VALUE="Don't Press
Press Me"
Me"
onClick="alert('now
onClick="alert('now you
you are
are in
in trouble!')“
trouble!')“ >>
</FORM>
</FORM>

37
Some Events (a small sample)

onUnLoad
onLoad Window events
onClick
onMouseUp Button events
onMouseDown
onDblClick
onMouseOver Link events

38
Document Object Model
• Naming hierarchy used to access individual elements of a HTML
document.
• Netscape D.O.M. is a little different than IE D.O.M. (D.A.M.)!!!*
• Easy to use if you name all entities:
• Forms, fields, images, etc.

Things are getting better all the time – there are


standard DOMs defined by The W3C
39
DOM example
<FORM ID=myform ACTION=…
Please Enter Your Age:
<INPUT TYPE=TEXT ID=age NAME=age><BR>
And your weight:
<INPUT TYPE=TEXT ID=weight NAME=weight><BR>
</FORM>

From javascript you can get at the age input


field as: document.myform.age.value

40
Form Field Validation

• You can have JavaScript code that makes sure the user enters valid
information.
• When the submit button is pressed the script checks the values of all
necessary fields:
• You can prevent the request from happening.

41
Checking Fields
function
function checkform()
checkform() {{
if
if (document.myform.age.value
(document.myform.age.value ==
== "")
"") {{
alert("You
alert("You need
need to
to specify
specify an
an age");
age");
return(false);
return(false);
}} else
else {{
return(true);
return(true);
}}
}}

Needs to return true or false!

42
Nee
bro ded
ws to p
The Form er fr r
om event
sub the
mi t
<FORM METHOD=GET ACTION=foo.cgi ting
<FORM METHOD=GET ACTION=foo.cgi !
NAME=myform
NAME=myform
onSubmit="return(checkform())">
onSubmit="return(checkform())">

AGE:
AGE: <INPUT
<INPUT TYPE=TEXT
TYPE=TEXT NAME=Age>
NAME=Age>
<INPUT
<INPUT TYPE=SUBMIT>
TYPE=SUBMIT>
</FORM>
</FORM>

43
Quiz 1 (5%)

• 1. write at least 3 uses of JavaScript (1pt)


• 2. write at least 2 predefined objects with their methods and
attributes. (1pt)
• 3. write a user defined JavaScript function that displays the sum of two
numbers entered from the form text field. (form name= adder textfiled
1 name = firstnum and text fild 2 name=secondnum) when the user
clicks the button. (3pts)

You might also like