[Go to site: main page, start]

0% found this document useful (0 votes)
9 views53 pages

JavaScript Programming Course Overview

This document provides an overview of JavaScript, covering its introduction, data structures, control structures, predefined classes, procedures and functions, event-driven programming, and browser objects. It emphasizes JavaScript's role in adding interactivity to HTML pages and includes examples of writing and executing JavaScript code. Key concepts such as variables, functions, event handling, and browser object properties are also discussed.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views53 pages

JavaScript Programming Course Overview

This document provides an overview of JavaScript, covering its introduction, data structures, control structures, predefined classes, procedures and functions, event-driven programming, and browser objects. It emphasizes JavaScript's role in adding interactivity to HTML pages and includes examples of writing and executing JavaScript code. Key concepts such as variables, functions, event handling, and browser object properties are also discussed.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming Course

WEB TECHNOLOGIES

Chapter 3
JavaScript Language
SUMMARY
1. Introduction
2. Data structures
3. Control structures
[Link] classes
5. Procedures and functions
Event-driven programming
7. The browser objects
8. The WINDOW class
9. The document class
[Link] processing
[Link] management
[Link] DOM
JAVASCRIPT

1. Introduction
Why JAVASCRIPT?
Main objective:
introduce interactivity with HTML pages
perform simple tasks on the workstation
from the user
Means: introducing small programs, called
SCRIPTS, in HTML pages
structured programming language that contributes to
enrich the HTML
JS is fully integrated into the HTML code
JS contains event handlers
Writing and executing JS code
JavaScript code can be placed in 3 locations:
Between the <SCRIPT> and </SCRIPT> tags
Associated with an HTML tag that manages a
event
Associated with the pseudo-protocol
in a URL
JSEntre the <SCRIPT> tags and
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
...code//code : instructions, function declarations,
etc..
</SCRIPT>
If it is included in the <HEAD> section, it is not
executed right away.
On the other hand, if it is part of the body of the document, it is
immediately executed at the same time as the code
HTML is interpreted.
It is necessary to include the statements of
functions in the <HEAD>..</HEAD> section
JS associated with an HTML tag
Calculate
> JS is generally inserted in the form of a
function call
Function previously declared in the
HEAD party
Linked to the pseudo-protocol
javascript
<A HREF="JavaScript:void(calculer())">
To calculate
This pseudo-URL allows you to launch
the execution of a script written in JS
The VOID operator allows you to ignore the
return parameter of the function
Example
<html>
<head>
<script>
function greet() { alert("Hello everyone!"); }
</script>
</head>
<body>
Immediate execution
<script>
alert("Hello everyone!");
</script>
<H4>Exécution sur événementonClick</H4>
<form>
<input type="button" name="Bouton1" value="Salut" ></form>
Execution on protocoljavascript:
to greet
</body>
</html>
JAVASCRIPT

2. Data structures
The constant data
JS provides the following constants directly
available:
the numerical constants: integers, reals written in
decimal notation, or floating (i.e. in notation
scientific, e.g.: 2718E-3
the 2 boolean constants: true or false
strings, surrounded by quotes ""
or apostrophes ' '
the constant specialnull means 'nothing', 'absence of
value". This value is assigned to any variable
used without being defined (for example prompt()
return null if the Cancel button is selected
Strings
JavaScript converts integers to strings.
characters, which allows to concatenate
names with strings
In the writing instruction in the document
current, [Link](), the data to display
can be separated by commas or +
Special characters can also be inserted.
in the chains: \b (backspace), \f (form feed)
, (new line), (enter), & (tab); ' for
an apostrophe
We can insert HTML codes in the form of
strings that will be well interpreted at execution
like real markers, and not displayed
as they are.
Example
<script>
[Link]("Here is the approximate value at ",
near the constant e:
3);
Mon
<i>high school</i> is located in <u>Aladarissa</u>
in the city of Fes
</script>
The variables
5 types of variables in JS.
Les nombres : number, les chaines : string,
the booleans: boolean, the objects
Example:
var chaine = 'bonjour';
[Link](typeof(string));
Tableau
Declaration
varnom_tableau=new Array(dimension);

Examples
var MyArray = new Array(8)
var Les4saisons = new Array("printemps",
"été", "automne", "hiver");
var month = new Array(12);
Paintings
Properties
give the number of elements.
var month = new Array(12);
There are
the year
var NbMois = [Link];
shared in
quarters";
Methods
reverse() changes the order of the elements
sort() trie in ascending order, or according to the
model indicated as parameter
JAVASCRIPT

3. Control structures
if ... [then] .. else
if (condition1 && / || condition2 ) then (then is
optional)
{ séquence 1 }
else
{ séquence 2 }
The condition must always be surrounded by ( )
Sequence 1 is executed if the condition is
true.
The sequence2 (optional) is executed if the
the condition is false.
Braces { } are not mandatory only in case
multiple instructions.
Switch … Case
The switch instruction evaluates an expression and, depending on
the obtained result and the associated case, execute them
corresponding instructions.
Syntax:
switch (expression)
{
case value1: /*Instructions to execute when the result of the expression matches
to value1*/
instructions1;
[break;]
case valeurN: /* Instructions to execute when the result of the value expression
instructionsN;*/
[break;]
default: /* instructions to be executed when none of the values // match
instructions_def; [break;] */
}
The controlled iteration FOR
for(initial value; condition; continuation)
{sequence of instructions}
an initial value or expression concerning
an integer variable called counter.
a condition: as long as it is true, the
rehearsal is ongoing.
a pursuit expression that consists of
the update of the meter.
Example
<SCRIPT language = "JavaScript" >
Square table<BR>
for (var i = 10; i <= 15; i++)
i = i² = +
i*i+"<BR>"); }
</SCRIPT>
The WHILE iteration
WHILE(condition){sequence of instructions }
<SCRIPT language = "JavaScript" >
function random(N) { return [Link]([Link]()*N)+1; }
max= prompt("Nombres au hasard de 1 à ","6");
<H2>Table of numbers between 1 and randomly drawn,
until obtaining ",max,"</H2>";
tab = new Array(10*max);
a = random(max);
tab[0] = a;
i=0;
while ( a != max ) { a = random(max); tab[i]= a; i ++ }
max was obtained in the i-th draw <P>
i=0;
while ( tab[i] != null )
{ [Link]("tab [", i,"] = ", tab[i],"---");
if (i % 5 == 0 && i != 0) [Link]("<br>");
i ++; };
</SCRIPT>
JAVASCRIPT

4. The predefined classes


Math Class
[Link](), square root.
[Link]() , [Link]() , [Link]() ,[Link] (),
[Link](), [Link]()
[Link](), [Link]() immediately integer
lower / higher.
[Link](base, exponent), power function, where base
and exponent are numerical expressions
any assessable.
[Link]() , [Link]()
[Link](), randomly chosen 'real' number in
[0 , 1[
[Link]() rounds to the nearest integer.
String Class
eval() numerically evaluates an arithmetic expression
provided in the form of a string.
parseInt(), returns an integer resulting from the conversion
if possible) from a string.
If the conversion is not possible, the returned value is 0.
parseFloat() gives a decimal number in the same way.
[Link](), to convert chaine to uppercase.
[Link](d, f) extracts a part of the string, starting from
position character d, up to f-1.
[Link](n) returns the character located in the nth position (n
from 0 to [Link]-1.
[Link](s_ch) gives the 1st position of the character of
chain equal to the 1st character of s_ch.
Date Class
Date(), to get the date and time
current (known to the system)
Date(month day, year hour:min:sec) for
obtain for example: December 25, 1995
13:30:00)
Date(year, month, day), a sequence
convenient of 3 integers, for example (2000,
7, 1)
JVASCRIPT

5. Procedures and functions


Procedures and functions
<HEAD>
<SCRIPT LANGUAGE=JavaScript >
functionName(param1, param2, ...)
{ séquence d'instructions; }
function functionName(param1, param2, ...)
sequence of instructions;
returnnom_variable }
</SCRIPT>
</HEAD>
Example
<HEAD>
<SCRIPT language="javascript">
function hello(firstName)
Hello, how are you
function volumeSphere(radius)
return 4/3*[Link]*[Link](radius,3);
function calculatePrice(UnitPrice, NumberOfItems)
{ return PrixUnitaire* NbArticles; }
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT language="javascript">
hello("Toto");
var amount = CalculatePrice(150, 4);
You must pay
Do you know that the volume of a sphere with a unit radius is
volumeSphere(1)," ?<BR>" );
</SCRIPT>
</BODY>
JAVASCRIPT

6. Event-driven programming
Events
onBlur: occurs when a Textarea, Text, or Select field is no longer active.
onChange: occurs when a Textarea, Text, or Select field is modified
by the user.
onClick:se produit quand un composant Button, Checkbox, Radio Link, Reset
or Submit receives a mouse click
onFocus: occurs when a Textarea, Text, or Select component is activated.
onLoad occurs when the browser has finished loading a window or all.
the frames of a FRAMESET. The onLoad event is positioned in the tag
BODY or in the FRAMESET tag
onMouseOver occurs when the mouse passes over a hyperlink or an area
activatable of an image.
onSelect the product when a Textarea or Text component is selected.
onSubmit: occurs when a form is globally validated
submitButton.
onUnload:se produit quand on quitte un document. L'événementonUnloadse
position in the BODY tag or in the FRAMESET tag.
onAbort: occurs when the user interrupts the loading of an image
onError: occurs when loading a page or an image produces
an error.
onMouseout: occurs when the mouse leaves an area's area of an image or
a hyperlink.
onReset: se produit quand on clique sur le boutonreset of a form
Text areas
<FORM NAME="Questions">
<INPUT TYPE="text" NAME="txtClasse" VALUE="" SIZE="10">
</FORM>
Le texte entré par l'utilisateur est affecté à la propriétévaluedu
composanttxtClasse
The content of the text field is accessible by its name.
complete
[Link]
it can be assigned to a variableMyClass using the expression:
MyClass = [Link]
Forms in the same document are stored in a
table called forms; the first form is then noted
forms[0], the second is forms[1] etc..
If Questions is positioned in the first form, we
can replace the previous assignment with:
MyClass = [Link][0].[Link]
the SELECT object
selectedIndex number of the selected item in
the list
var num = [Link]
options[] is the predefined array containing the
items of the list
[Link][num] is the field object located at No.
num (reminder: the first has the number 0)
[Link][num].value is the value of the option
No. number of the list.
[Link][num].text is the following text
champ <OPTION>.
RADIO buttons

[Link][num] is the radio button No. num (the


1st is the number 0) of the set of buttons
named choice
check the boolean describing the state of a
button: if ([Link][num].checked) ....
[Link][num].value is the associated value
at button No. serial number of the button.
Checkboxes
The treatment is completely similar to the
in the case of radio buttons, unlike
each box has a distinct proper name
of others. The state checked of each box
must therefore be tested individually.
See the complete example that follows.
JAVASCRIPT

7. The objects of the browser


Hierarchy of objects
browser classes
navigator: it is the client software whose name is noted
in [Link]
window: the highest level object created by the
browser, it is its window.
location: it is the URL object of the current window.
history: ce sont les URL précédemment visitées.
this is the current document, of which the
propriétés sont le titre, les couleurs (fond, texte, lien
...), the forms, the images, etc..
Properties of the OBJECT WINDOW

Protocol used:
[Link]
URL :[Link]=
[Link]
[Link]/util/programmation/javascript/J
our3/[Link]
Status bar message:
[Link]
Properties of the OBJECTDOCUMENT
Titre du document :[Link]=
JavaScript Course
Text color: [Link]=
#000000
Couleur du fond :[Link]=
#f1f1f1
Properties of the navigator object

[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
JAVASCRIPT

8. The WINDOW class


Properties 1
defaultStatus: représente le message de défaut qui sera affiché dans
the status bar
Hello everyone
status is a message displayed in the status bar of the window.
[Link]="Don't forget to close your windows!"
length represents the number of frames in the parent window (0
otherwise).
name represents the name of the window
specifies the name of the parent window that created it
dynamically, with open().
parent the name of the frame where the window is possibly located
selfest is a synonym for the name of the window and refers to the
current window
top refers to the main window of the browser.
window is a synonym for the current window
Boolean indicating whether the window has been closed.
usage: if (! [Link]) [Link]();
Properties 2
this is the HTML document studied
history list of documents loaded in the window (simulates the action
next and previous buttons)
[Link]() : previous document
[Link]() : the next
[Link](n) : reloads the document located n steps from the present
document (is of sign any)
location
[Link] : string containing the url
[Link]: part of the URL after # (internal link)
[Link] : server name and port
[Link] : http, ftp, javascript, ..
[Link]() : reloads the current document = [Link](0)
[Link](url)
frames[] is an array representing all the frames in a window
The frame windows can be named at the time of their
definition by a name, otherwise they can be referenced by frames[index]
Window management methods
With open() and close(), the programmer can open and close
auxiliary windows
window=open("URL","window_name", "options"); opens a
new window
"URL" is the address of the document to be loaded in the new.
window.
"nom_fenetre" is the name of the window, to be assigned to the attribute.
TARGET of the <FORM> or <A> tags
"options" is a list of optional items that specifies
the appearance of the window.
We then use the name window to refer to a
object or a property of the new window.
For example, to write in the message component of the
form located in the window doc of the window fen,
created by fen=open(...), we write:
[Link] = "...";
Options section settings

toolbar toolbar[=yes|no] | [=1|0]


url visible location[=yes|no] | [=1|0]
directory? directories[=yes|no] | [=1|0]
status bar status[=yes|no] | [=1|0]
menu bar menubar[=yes|no] | [=1|0]
scroll bar scrollbars[=yes|no] | [=1|0]
resizing resizable[=yes|no] | [=1|0]
permanent visibility? alwaysRaised[=yes|no] | [=1|0]
closed with the parent window dependant[=yes|no] | [=1|0]
height height= dimension in pixels
width width= dimension in pixels
positioning X screenX = nb pixels
Y positioning screenY = nb pixels
JAVASCRIPT

9. The document class


Tables of the document object
anchors[] table of internal links <A NAME= ...>
applets[] applet table <APPLET CODE=...>
embeds[] table of inserted objects <EMBED
..>
forms[] table of forms <FORM >
elements[] form component table
<INPUT ..>, <SELECT ..>, ..
images[] table of images <IMG SRC=...>
links[] table of hyperlinks <A HREF= ...>
Main properties
Document Title
Text color: [Link]
Background color: [Link]
Link color: [Link]
Color of visited links: [Link]
Color of active links: [Link]
Document address : [Link]
Date of last modification:
[Link]
The cookie of the document: [Link]
Main methods
write(ch1, ch2, ..) displays the strings or
arguments translated into strings.
open() creates a new document, does not
not to be confused with the creation of a
window!
close() closes the document, impossible
then add some text.
getSelection() gives the text
selected
JAVASCRIPT

10. Image processing


Properties
var myImage = new Image()
Properties
They correspond to the attributes of the <IMG> tag
name, src, lowsrc, height, width, border, hspace, vspace ..
The most important property allows loading the
image file from a URL and store it in the object.
var myImage = new Image(); [Link] = "[Link]";
But the image is not displayed. It may be displayed in a
tag <IMG>
<IMG SRC=...>
Furthermore, unfortunately, the height and width properties do not
are not modifiable
Example
Here is an image that serves as a link
When the user moves their mouse, it causes
un événement onMouseOver qui doit changer la
source of the image
When he leaves it, the onMouseOut event is
provoked and the initial image will be displayed again
<A HREF="javascript:void(0)">
"
<IMG
NAME="img" SRC="../images/[Link]"></A>

You might also like