0% found this document useful (0 votes)
34 views18 pages

JavaScript Basics: A Comprehensive Guide

The document provides an introduction to JavaScript, detailing its role in creating interactive web applications and its integration with HTML. It covers the syntax, variable declaration, data types, and various methods for input and output, as well as the structure of JavaScript scripts. Additionally, it discusses JavaScript objects, including predefined entities and user-defined types, and outlines the properties and methods associated with browser and document objects.

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)
34 views18 pages

JavaScript Basics: A Comprehensive Guide

The document provides an introduction to JavaScript, detailing its role in creating interactive web applications and its integration with HTML. It covers the syntax, variable declaration, data types, and various methods for input and output, as well as the structure of JavaScript scripts. Additionally, it discusses JavaScript objects, including predefined entities and user-defined types, and outlines the properties and methods associated with browser and document objects.

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

03/02/2021

Cadi Ayyad University ‫ﺽﻋﻴﺎﺿﻲﻟﻘﺎﺍ ﺓﻉﺟﺎﻡ‬


Multidisciplinary Faculty
‫ﺕﺧﺼﺼﺎﺕﺍﻝ ﺓﺩﺩﺗﻊﻟﻢﺍ ﻳﺔﻝﻟﻚﺍ‬
Department of Mathematics and
Computer Science ‫ﺕﻹﻉﻻﻣﻴﺎﺍﻭﻳﺎﺕﺽﻟﺮﻳﺎﺍ ﺑﺔﻉﺵ‬
Pure ‫ﻱﺁﺳﻒ‬

JavaScript: Introduction

Pr. YOUSSEF MOURDI


[Link]@[Link]

Introduction

JavaScript allows making a website interactive developed in


HTML.
JavaScript allows for the development of real applications
operating exclusively within the framework of the Internet.

JavaScript is a simplified object-oriented scripting language that


Syntax is based on that of Java.
JavaScript was originally developed by Netscape in collaboration with
Sun Microsystem.
Later, Microsoft will develop its own programming language Javascript officially known as the
JScript name.

03/02/2021 [Link] 2

1
03/02/2021

Introduction

Unlike a Java applet which is a compiled program, the


scripts written in Javascript are interpreted
Java, represented by one or more standalone files with the extension
sera*.classou*.jar is invoked by a specific HTML tag
JavaScript iswrite directly within the HTML document in the form
of a script framed by special HTML tags or in a file
separated called with special HTML tags.

JavaScript is standardized by a specialized committee, ECMA (European)


Computer Manufacturers Association.

03/02/2021 [Link] 3

HTML and JavaScript

The HTML page must ALWAYS contain both tags.


specific and essential
<script language="JavaScript">
............
</script>

JavaScript code integrates in two ways with the code


HTML
1. Insertion directed in the HTML code
JavaScript code is most often embedded in the HTML page itself.
It is the simplest and most commonly used method by developers.
Internet sites.

•2. Insertion as an external module


03/02/2021 [Link] 4

2
03/02/2021

Insertion into an HTML page

There are 2 ways to insert JavaScript code into an HTML page


1.1 Insertion for direct execution
<html>
The code runs automatically <head>
when loading the HTML page <title>..... </title>
in the browser at the same time as </head>
<body>
the content of the HTML page
<script language="JavaScript">
is displayed on the screen.
alert('hello');
</script>
The JavaScript code is placed </body>
in the very body of the HTML page, </html>
between the <body> tags......... And
.........</body>
03/02/2021 [Link] 5

2. Insertion by calling an external module

You can insert JavaScript code by calling an external module.


located at any address (URI).
<script src="URL of the external module">
............
</script>

The two Javascript tags must be placed between the <body> and </body> tags
in the case of a direct execution or between the <head> and </head> tags of the page
HTML for deferred execution.
Stored in a file on the server at its call address in the form of TEXT
IMPORTANT the extension .txt or .js
Simplifies the maintenance of sites using common JavaScript modules
to several HTML pages.

03/02/2021 [Link] 6

3
03/02/2021

Data input and output with JavaScript

3 types of message boxes can be displayed using Javascript:


Alert, Confirmation and Invitation

alert() method
•is used to display simple text-type information to the user. Once the latter has read it,
He must click OK to make the box disappear.
confirm() method
allows the user to choose between the OK and Cancel buttons.
•prompt() method
The prompt() method allows the user to type their own message in response to the question.
posed

The [Link] allows you to write HTML code on the WEB page
03/02/2021 [Link] 7

Data entry and output with JavaScript

<html>
<head>
<title> une page simple </title>
</head>
<body>
Hello
<script language='javascript'>
alert('hello');
[Link] (
prompt('What is your name?', 'Please enter your name here')
);
confirm('which button will you choose?');
</script>
</body>
</html>
03/02/2021 [Link] 8

4
03/02/2021

The structure of a script in JavaScript

The syntax of the Javascript language is based on the model of Java and C.
General rules
• The insertion of spaces can be done anywhere in the script.
• Each command must end with a semicolon (;).
• A decimal number is separated by a point (.) and not by a comma.
• The JavaScript language is case-sensitive.
• There are two methods to integrate comments into your
scripts.
• Place a double slash (//) in front of the text
• Frame the text with a slash followed by a star (/*) and the same sequence reversed.
(*/)

03/02/2021 [Link] 9

The variables

Declaration and assignment


The keywordallowed to declare one or //Declaration of, reject of.
several variables. var i, j, k;

After the declaration of the variable, it is Assignment of funds.


possible to assign a value to it by i = 1;
//Declaration and assignment of prices.
the intermediary of the equal sign (=).
var price = 0;
If a value is assigned to a variable
//Declaration and assignment of character
without it being declared, var caractere = ["a", "b", "c"];
so Javascript the declare
automatically.

03/02/2021 [Link] 10

5
03/02/2021

The variables

Declaration and assignment


Reading an undeclared variable causes an error

A properly declared variable but without any value assigned is undefined.


(undefined).

The scope
Variables can be global or local.

A global variable is declared at the beginning of the script and is accessible from anywhere.
place of the program.

A local variable is declared inside a function and can only be used within the function.
function itself.
03/02/2021 [Link] 11

The variables
The type of a variable depends on the value stored in that variable.
type declaration.
•var maVariable= ‘Philippe’;
maVariable =10;
three main types of values
String
Number10^-308 < number < 10^308
Integers
floating point decimal numbers
3 special values:
Positive Infinity or +Infinity (positive infinite value)
•Negative Infinity ou–Infinity (valeur infinie négative)
•Nan (Not a Number) usually generated as a result of an operation
incoherent mathematics
Boolean
two literal values: true (true) and false (false).

03/02/2021 [Link] 12

6
03/02/2021

Special values

JavaScript also includes two special data types:


Null has a single value, null, which means absence of data in a variable.

•Undefined: has a single value, undefined. A variable whose content is not


clear that Ellen never stored any value, not even a defined one (undefined).

03/02/2021 [Link] 13

Operations on strings
Concatenation
var chain = " hello " + " FI3/FCD1 ";

Determine the length of a string


var ch1 = " hello ";
var length =[Link];

Identify the n-th character of a string


Hello again!
var carac =[Link](2);

Extraction of a part of the chain


•Var dateDuJour = " 04/04/03 "
var month =[Link](3, 5);
3: is the index of the first character of the substring to extract
•5 : index of the last character to be considered; this character will not be
part of the substring to extract
03/02/2021 [Link] 14

7
03/02/2021

The predefined functions

•eval
This function executes JavaScript code from a string.

...
<SCRIPT LANGUAGE="JavaScript">
function evaluation() {
[Link]=eval([Link]); }
</SCRIPT>
...
<FORM NAME="form">
Enter a mathematical expression: <INPUT TYPE="text" NAME=saisie MAXLENGTH=40 SIZE=40>
<INPUT TYPE="button" VALUE="evaluation." onClick="evaluation()">
<INPUT TYPE="text" NAME=calcul MAXLENGTH=40 SIZE=40>
</FORM>...

03/02/2021 [Link] 15

The predefined functions


Number
converts the specified object to a numeric value
var day = new Date("December 17, 1995 03:24:00"); // convert the date into milliseconds
alert (Number(jour));

String
converts the specified object to a string
day = new Date(430054663215); // Converts the number into date Month day, Year etc.
alert(String(day));

Escape
returns the hexadecimal value from a string encoded in ISO-Latin-1.

!&//return!&%

03/02/2021 [Link] 16

8
03/02/2021

The Objects
JavaScript objects are either predefined entities of the language or
created by the programmer.
For example, the browser is an object called "navigator
The browser window is called 'window
The HTML page is another object, which we call "document
A form inside a "document is also an object.
A hyperlink in an HTML page is yet another object. It is called "link.
etc...
JavaScript objects can respond to 'Events'.
Not all browsers support the same objects
Access to the properties of an object
•[Link]
•[Link] = verte
03/02/2021 [Link] 17

Les Objets

The New operator


The newest operator used to create a new instance or a new type of object
defined by the user or one of the predefined object types,Array, Boolean, Date, Function,
Image, Number, Object, orString.

new_object = new object_type(parameters)

A string of characters

03/02/2021 [Link] 18

9
03/02/2021

Les Objets

The typeof operator


The typeof operator returns a string indicating what the type is
the operand.

var i = 1;
typeofi;//returnsnumber
var titre="Les raisins de la colère";
typeof title; //returnsstring
var jour = new Date();
typeofjour;//returnsobject
var choice = true; typeofchoice;//returnsboolean
var cas = null; typeofcas;//returnsobject
typeof parseFloat; //returnsfunction
typeofMath; // returns object (IE 5.*, NS 6.*, NS 4.78, Opera 6.*, Opera 5.*
typeofMath; // returns function NS 3.*, Opera 3.*

03/02/2021 [Link] 19

The string object

Property:
•length: retourne la longueur de la chaîne de caractères;
Methods:
•anchor( ): formats the string with the named <A> tag;
•b( ): format the string with the <B> tag; to be reviewed !!
•big( ): formats the string with the <BIG> tag;
charAt( ): returns the character located at a certain position;
charCodeAt(): returns the code of the character at a certain position;
concat(): allows you to concatenate 2 strings;
fromCharCode( ): returns the character associated with the code;
indexOf( ): allows you to find the index of occurrence of a character in a string;

03/02/2021 [Link] 20

10
03/02/2021

The string object

•italics( ): format the string with the <I> tag;


lastIndexOf(): allows you to find the last index of occurrence of a character;
•link( ): format the string with the <A> tag to create a link;
slice( ): returns a portion of the string;
substr( ): returns a portion of the string;
substring( ): returns a portion of the string;
toLowerCase( ): allows you to convert the entire string to lowercase;
toUpperCase( ): allows the entire string to be converted to uppercase;

03/02/2021 [Link] 21

The array object

Property:
•length: retourne le nombre d'éléments du tableau;
Methods:
•concat( ): allows you to concatenate 2 arrays;
join( ): converts an array into a string;
reverse( ): inverses the ranking of the elements in the array;
slice(): returns a section of the array;
•sort( ): allows for the sorting of array elements;

03/02/2021 [Link] 22

11
03/02/2021

The browser objects

The highest object in the hierarchy iswindow that corresponds to the window
even from the browser.

The objectdocument refers to the content of the window.


documentgroup together all HTML elements within properties
present on the page. To reach these different elements, we will use:
either methods specific to the objectdocument, like the method getElementById( ),
which allows to find the element based on its identifier (ID);
- either collections of objectswhich group all the
elements of a determined type.
03/02/2021 [Link] 23

Browser objects

March 2, 2021 [Link] 24

12
03/02/2021

The window object

Properties: (accessible with IE and N)


closed: indicates that the window has been closed;

•defaultStatus: indique le message par défaut dans la barre de status;

•document: retourne l'objetdocumentde la fenêtre;

•frames: retourne la collection de cadres dans la fenêtre;

•history: returns the browsing session history;

location: returns the currently visited address;

•name :indique le nom de la fenêtre;

03/02/2021 [Link] 25

The window object

•navigator: returns the browser used;

•opener: retourne l'objetwindowqui a créé la fenêtre en cours;

•parent: returns the immediate parent object in the hierarchy;

•self: returns the window object corresponding to the current window;

•status: indique le message affiché dans la barre de status;

top: returns the highest window object in the hierarchy.

03/02/2021 [Link] 26

13
03/02/2021

The window object

Methods:
•blur( ): removes the focus from the window;
close( ): closes the window;
•focus(): sets the focus on the window;
moveBy( ): moves by a distance;
moveTo( ): moves the window to a specified point;
open( ): opens a new window;
print( ): prints the content of the window;
•resizeBy( ): resizes by a certain ratio;
resizeTo( ): resizes the window;
setTimeout(): evaluates a string after a certain period of time.

03/02/2021 [Link] 27

The document object

Properties:
•applets: returns the collection of Java applets present in the document;
•cookie: allows to store a cookie;
•domain: indicates the domain name of the server that provided the document;
forms: returns the collection of forms present in the document;
•images: retourne la collection d'images présentes dans le document;
•links: returns the collection of links present in the document;
•referrer: indique l'adresse de la page précédente;
•title: indique le titre du document.
Methods:
close( ): closes the document for writing;
open( ): opens the document for writing;
write( ): writes in the document;
•writeln( ): writes to the document and performs a line break
03/02/2021 [Link] 28

14
03/02/2021

The events

JavaScript is event-driven
occur during various actions on the objects of an HTML document.
onLoad;
onClick
onMouseover
onMouseout
onChange
•…

It is possible to base the execution of functions on events.

03/02/2021 [Link] 29

The events
•Evénement onLoad
It occurs when a web page is loaded in the browser window.

The entire page (including the images it contains if their loading is planned) must
having been charged for it to take place

This event can only be associated with an image; in which case, it occurs a
once its loading is complete

alert('page loaded');
Example of the onLoad event
</BODY></HTML>

03/02/2021 [Link] 30

15
03/02/2021

The events
•Click Event
It occurs when the user clicks on a specific element on a page, such as
a hyperlink, an image, a button, text, etc.

These elements are capable of responding separately to this event.

It can also be triggered when the user clicks anywhere on the page if
has been associated not with a specific element, but with the entire body element

<HTML><BODY>
<INPUT TYPE="Button" Value="click here" onClick="alert('Click')">
</BODY></HTML>

03/02/2021 [Link] 31

The events
Mouseover event
Similar to onClicks, it is enough for the user to place their mouse pointer over one
the aforementioned elements (hyperlink, image, button, text, etc.) for it to take place

Mouseout event
•A l’inverse deonMouseover, cet événement se produit lorsque le pointeur de la souris
leaves the selection area of an element.

<HTML><BODY>
<IMG SRC="[Link]" onMouseOver="src='[Link]';"
onMouseOut="src='[Link]';">
</BODY></HTML>

03/02/2021 [Link] 32

16
03/02/2021

Naming of objects
To be able to manipulate an object in JavaScript, it must have a name.

To distinguish the different object-elements of a web page, it is enough to their


give a name through the attribute NAME
•<Table Name="tableau1">…
•<Table Name="tableau2">…
•<Form Name = "form1">…
•<Form Name ="formulaire2 ">…

In the case where the object is unique, there is no need for a name to designate this object.
Example: the case of BODY (only one BODY per document), DOCUMENT (only one DOCUMENT)
by window

03/02/2021 [Link] 33

Manipulation of objects
To address an object, it is not enough to give its name: one must also
specify its "access path" in the hierarchy of the structure

<HTML><BODY
onLoad="[Link]='Hello';">
<FORM name="form"><INPUT NAME="field" TYPE="text">
</FORM></BODY></HTML>

If the window name is omitted, the browser will default to the window
current
In the case of frames, it is relevant to give the name of the window.
It is also possible to omit [Link]: the addressing succeeds since it
There is only one object 'document' in the window.
03/02/2021 [Link] 34

17
03/02/2021

Manipulation of form objects


Element <input…>

Properties Methods
namefield name focusgive the focus (cursor)
blurremove the focus
typetype of field (text, button, radio,
•clicksimulate a click (on a button)
checkbox, submit, reset
Events
valuetext value
onFocusdetects the focus grab
sizefield size onBlurdetects loss of focus
maxlengthmaximum size of a text field onClickdetects a click
checkedcheckbox / radio button checked or not onChangedetects changes
disabledgrayed out (modification not possible)
readOnlyread-only
classstyle class name
stylename of the style
03/02/2021 [Link] 35

Manipulation of form objects


Element <input…>

Element <input type="text">

Accepted properties
•name, value, defaultvalue, size, maxlength, disabled, readOnly, class, style
Accepted methods
focus, blur
Accepted events
•onFocus, onBlur, onChange

03/02/2021 [Link] 36

18

You might also like