ifi7174 lesson3

62
IFI7174.DT – Lesson 3 JavaScript

Upload: sonia

Post on 22-Jan-2018

3.041 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Ifi7174 lesson3

IFI7174.DT – Lesson 3

JavaScript

Page 2: Ifi7174 lesson3

JavaScript

• Is a lightweight

– Object Oriented Programming (OOP) language

• Why JavaScript?

– It helps you to add behaviors into your webpages

– It changes HTML Content

– It changes HTML Styles (CSS)

2015 @ Sonia Sousa 2

Page 3: Ifi7174 lesson3

JavaScript

• Is typically used in browsers

– to power dynamic websites.

• add functionality;

• validate input, and

• communicate with web servers

• JS code is loaded and ran

– Inline within HTML code <script> tags

– In blocks

• <script> JS code </script>

2015 @ Sonia Sousa 3

Page 4: Ifi7174 lesson3

JavaScript

• Can be:

– Load as an external scripts

• External

– Inline within HTML code <script> tags

– Embedded

• <head>– functions

• <body>– event change

<script src="myScript.js"></script>

<script>document.write("<h1>Hello, there!</h1>"); </script>

<head>

<title>Embedded JS Example</title>

<script>

document.write("Oops");

</script>

</head>2015 @ Sonia Sousa 4

Page 5: Ifi7174 lesson3

External JS Advantages

• It separates HTML and code

• It makes HTML and JavaScript easier to read and maintain

• Cached JavaScript files can speed up page loads

2015 @ Sonia Sousa 5

Page 6: Ifi7174 lesson3

JS Embedded in HTML

<script>function myFunction(){document.write("Oops! The document disappeared!");}</script>

<button onclick="myFunction()">Try it</button>

• <head> </head>

• <body> </body>

2015 @ Sonia Sousa 6

Page 7: Ifi7174 lesson3

JS inline with HTML

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>function myFunction() {

document.getElementById("demo").innerHTML = "Paragraph changed.";}</script>

2015 @ Sonia Sousa 7

• <body> </body>

Page 8: Ifi7174 lesson3

The Document Object

• When an HTML document is loaded into a web browser, – it becomes a document object.

• The document object – provides properties and methods

• to access all node objects, from within JavaScript

– represents • the root node of the HTML document

– It controls the• element, text, attribute, and comment nodes

2015 @ Sonia Sousa 8

Page 9: Ifi7174 lesson3

Document Object Model (DOM)

• starts by…1. browser window itself

2. document page,

3. the elements included on the page; and

4. their attributes.

Source: Wikipedia

The object hierarchy

2015 @ Sonia Sousa 9

Page 10: Ifi7174 lesson3

How JS and the DOM cooperate

• When a web page is loaded,

– The browser creates a DOM of the page

• Like a tree

Source: w3schools2015 @ Sonia Sousa 10

Page 11: Ifi7174 lesson3

DOM

Window

document

meta

TextboxRadio button

head body

form[] link Imagestitle div ul

li

Establish the Order of things

2015 @ Sonia Sousa 11

Page 12: Ifi7174 lesson3

How JS and the DOM cooperate

• JavaScript can change

– the HTML elements in the page

– the HTML attributes in the page

– the CSS styles in the page

• JavaScript can react to

– the events in the page

• This is done by

– object notation

2015 @ Sonia Sousa 12

Page 13: Ifi7174 lesson3

Object notation

• Access to elements

– be referenced using dot notation

• starting with the highest-level object – (i.e., window).

» But as the window is in the top hierarchy do not need to be refereed

– Objects can be referred to

• by name; or id; or by their position on the page

document.getElementById("demo").innerHTML = "Hello JavaScript”;

2015 @ Sonia Sousa 13

Page 14: Ifi7174 lesson3

JavaScript Syntax

• Basic rules

– Ends with ; (semi-colons)

– ! is case sensitive !

• Comments

– double slash (//)

• 1 line comment

– between /* and */

• More than 1 line comment

2015 @ Sonia Sousa 14

Page 15: Ifi7174 lesson3

JS programs

• A program is a

– list of "instructions” to be "executed" by the computer

– These instructions are called statements

• JS statements are separated by semicolons ;

• A statement composed of:

– Values, Operators, Expressions, Keywords, and Comments.

2015 @ Sonia Sousa 15

Page 16: Ifi7174 lesson3

JavaScript statements

• Statements includes

– Values, Operators, Expressions, Keywords, and Comments

– Values are

• Literal or variables

– Functions are

• a block of code that can execute some action

– Events are

• actions triggered by someone

2015 @ Sonia Sousa 16

Page 17: Ifi7174 lesson3

Values

• Literal values are

– Numbers

• with or without decimals (10.50 or 1001)

– Strings

• Double or single quotes ("John Doe” ‘John Doe’)

– Variables

• Are used to store data (var x; x = 6;)

2015 @ Sonia Sousa 17

Page 18: Ifi7174 lesson3

JS Keywords

• To identify the JavaScript action to be performed.

Keyword Description

break Terminates a switch or a loop

continue Jumps out of a loop and starts at the top

do ... whileExecutes a block of statements, and repeats the block, while a condition is true

for Marks a block of statements to be executed, as long as a condition is true

function Declares a function

if ... else Marks a block of statements to be executed, depending on a condition

return Exits a function

switch Marks a block of statements to be executed, depending on different cases

try ... catch Implements error handling to a block of statements

var Declares a variable

2015 @ Sonia Sousa 18

Page 19: Ifi7174 lesson3

JS Statements

• A statement is the line of code that tell

– the browser to execute somethingdocument.getElementById("demo").innerHTML = "Hello!";

• JavaScript statementsVar x = 5;

var y = 6;

var z = x + y;

document.getElementById("demo").innerHTML = z;

2015 @ Sonia Sousa 19

Page 20: Ifi7174 lesson3

JavaScript Statements

• Giving a command to the browser

<script>function myFunction(){document.write("Oops! The document disappeared!");}</script>

<button onclick="myFunction()">Try it</button>

<script>function myFunction(){document.write("Oops! The document disappeared!");}</script>

2015 @ Sonia Sousa 20

Page 21: Ifi7174 lesson3

JS code and Blocks

JS code blocks

JS functions<script>function myFunction(){document.write("Oops! The document disappeared!");}</script>

<script>1. document.write("<h1>Hello, there!</h1>");2. document.getElementById("demo").innerHTML="Hello Dolly";3. document.getElementById("myDIV").innerHTML="How are you?”;</script>

• Define statements to be executed together

• JavaScript functions are statements grouped in blocks

2015 @ Sonia Sousa 21

Page 22: Ifi7174 lesson3

JS and HTML Styles (CSS)

• JavaScript can change

– HTML elements

– (CSS) Styles

– Or validate input (data)

• Using methods, conditional and fuctions

• For instance, to change the text

– It uses getElementById() methoddocument.getElementById("demo").innerHTML = "Hello

JavaScript”;

2015 @ Sonia Sousa 22

Page 23: Ifi7174 lesson3

JavaScript Variables

• variables are "containers" of information

– We can name it using letters (like x)

• The variable can contain

– Letter, numerical values or expressions

var x=5;var y=6;var z=x+y;

"declaring" a variable

assign a value

var carname;

carname="Volvo";

2015 @ Sonia Sousa 23

Page 24: Ifi7174 lesson3

Declaring (Creating) JS Variables

• Primitive data types

– Number

var x = 5;

– String

var carname = “Volvo XC60";

– Boolean

var x = true;

var y = false;

2015 @ Sonia Sousa 24

Page 25: Ifi7174 lesson3

Declaring (Creating) JS Variables

• JS Arrayvar cars=new Array();

cars[0]="Saab";

cars[1]="Volvo";

cars[2]="BMW";

var cars = ["Saab", "Volvo", "BMW"];

• JavaScript Objectsvar person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

2015 @ Sonia Sousa 25

Page 26: Ifi7174 lesson3

Object (Properties and Methods)

• data (variables) as objects

– they have properties

– they have methods

Object Properties Methods

Car car.name = Fiat

car.model = 500

car.weight = 850kg

car.color = white

car.start()

car.drive()

car.brake()

2015 @ Sonia Sousa 26

Page 27: Ifi7174 lesson3

JS Operators

• Operators are used to

– assign values to variables using (=)

• var x = 5; var y = 6;

• Arithmetic operators

• Comparison operators

• Logical operators

Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

++ Increment

-- Decrement

2015 @ Sonia Sousa 27

Page 28: Ifi7174 lesson3

JS Operators

Opera

torsexample results

+ x=y+2 Addition x=7

- x=y-2 Subtraction x=3

* x=y*2 Multiplication x=10

/ x=y/2 Division x=2.5

++ x=++y Increment x=6

-- x=--y Decrement x=4

== x==8 equal to false

!= x!=8 Not equal to true

> x>8 greater than false

< x<8 less than true

>= x>=8 greater than or equal to false

<= x<=8 Less tan or equal to true

&& (x < 10 && y > 1) and true

|| (x==5 || y==5) or false

! !(x==y) not trueLogical

Comparison

Arithmetic

2015 @ Sonia Sousa 28

Page 29: Ifi7174 lesson3

Assignment Operators

Operator Example Same asResul

t

= x=y

+= x+=y x=x+y

-= x-=y x=y-2

*= x*=y x=x*y

++ x=++y Increment x=6

-- x=--y Decrement x=4

== x==8

!= x!=8

> x>8

< x<8

>= x>=8

<= x<=8

&& (x < 10 && y > 1)

|| (x==5 || y==5)

! !(x==y)

2015 @ Sonia Sousa 29

Page 30: Ifi7174 lesson3

JS Expressions

• Combine values, variables, and operators

– The computation is called an evaluation

• 5 * 10 evaluates to 50

– can also contain variable values

• x * 10

• "John" + " " + "Doe"

2015 @ Sonia Sousa 30

Page 31: Ifi7174 lesson3

JavaScript Functions

• is a block of code designed to perform a particular task.

– A JavaScript function is executed when "something" invokes it (calls it).

function name(parameter1, parameter2, parameter3) {

code to be executed

}

2015 @ Sonia Sousa 31

Page 32: Ifi7174 lesson3

Function Syntaxfunction name(parameter1, parameter2, parameter3) {

code to be executed}

<!DOCTYPE html><html><head><script>function myFunction(){alert("Hello World!");}</script></head>

<body><button onclick="myFunction()”> Try it </button></body></html>

Function name

Code to execute

Call function

2015 @ Sonia Sousa 32

Page 33: Ifi7174 lesson3

Function Invocation

• The code inside the function will execute when "something” happens

– an event occurs (when a user clicks a button)

– it is invoked (called) from JavaScript code

– Automatically (self-invoked)

2015 @ Sonia Sousa 33

Page 34: Ifi7174 lesson3

JavaScript Functions

• A block of code that will be executed when "someone" calls it

<script>function myFunction(){document.write("Oops! The document disappeared!");}</script>

<button onclick="myFunction()">Try it</button>

<script>function myFunction(){document.write("Oops! The document disappeared!");}</script>

Code Block

Call function

2015 @ Sonia Sousa 34

Page 35: Ifi7174 lesson3

Return values

• Functions often compute a return value.

var x = myFunction(4, 3);

// Function is called, return value will end up in x

function myFunction(a, b) {

return a * b;

// Function returns the product of a and b

}

2015 @ Sonia Sousa 35

Page 36: Ifi7174 lesson3

Function with Arguments

</head> <body>

<button onclick="myFunction()">Try it</button>

<button onclick="myFunction('Bob','Builder')">Try it</button>

<script>function myFunction(name,job){alert("Welcome " + name + ", the " + job);}</script>

2015 @ Sonia Sousa 36

<script>myFunction(argument1,argument2){some code}</script>

Page 37: Ifi7174 lesson3

Using ID with function

</head> <body><p id="demo"></p>

<script>document.getElementById("demo").innerHTML=myFunction(4,3);</script>

<script>function myFunction(a,b){return a*b;}</script>

2015 @ Sonia Sousa 37

<script>myFunction(argument1,argument2){some code}</script>

Page 38: Ifi7174 lesson3

JavaScript Events

• Is something the browser does, or something a user does– Event handlers

• used to handle, and verify, user input, user actions, and browser actions.

– HTML events• An HTML web page has finished loading• An HTML input field was changed• An HTML button was clicked

<some-HTML-element some-event="some JavaScript">

<button onclick="this.innerHTML=Date()">The time is?</button>

2015 @ Sonia Sousa 38

Page 39: Ifi7174 lesson3

HTML DOM Events

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseoutThe user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

onmouseenter occurs when the pointer is moved onto an element

onmousedown the user presses a mouse button over an element

2015 @ Sonia Sousa 39

Page 40: Ifi7174 lesson3

JavaScript Strings

• String have Properties and Methods

– Primitive value

• var firstName = "John”var x = "John";

– String objects

• var firstName = new String("John")var y = new String("John");

2015 @ Sonia Sousa 40

Page 41: Ifi7174 lesson3

JavaScript StringsMethod Description

charAt() Returns the character at the specified index (position)

concat() Joins two or more strings, and returns a copy of the joined strings

indexOf()Returns the position of the first found occurrence of a specified value in a string

lastIndexOf()Returns the position of the last found occurrence of a specified value in a string

localeCompare() Compares two strings in the current locale

replace() Searches a string for a value and returns a new string with the value

search() Searches a string for a value and returns the position of the match

split() Splits a string into an array of substrings

toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale

toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale

toLowerCase() Converts a string to lowercase letters

toString() Returns the value of a String object

toUpperCase() Converts a string to uppercase letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the primitive value of a String object

2015 @ Sonia Sousa 41

Page 42: Ifi7174 lesson3

JavaScript Numbers

• toString() Method

– returns a number as a string

var x = 123;

x.toString();

// returns 123 from variable x

(123).toString();

// returns 123 from literal 123

(100 + 23).toString();

// returns 123 from expression 100 + 23

2015 @ Sonia Sousa 42

Page 43: Ifi7174 lesson3

JavaScript Math Object

• Allows you to perform mathematical tasks.

Math.random(); // returns a random number

Math.min() Math.max()

Math.random()

Math.round()

2015 @ Sonia Sousa 43

Page 44: Ifi7174 lesson3

JavaScript Dates

• lets you work with dates

– Date()

– Date(milliseconds)

– Date(dateString)

– Date(year, month, day, hours, minutes, seconds, milliseconds)

<script>

var d = new Date();

document.getElementById("demo").innerHTML = d;

</script>

2015 @ Sonia Sousa 44

Page 45: Ifi7174 lesson3

Date and time MethodsMethod Description

getDate() Get the day as a number (1-31)

getDay() Get the weekday as a number (0-6)

getFullYear() Get the four digit year (yyyy)

getHours() Get the hour (0-23)

getMilliseconds() Get the milliseconds (0-999)

getMinutes() Get the minutes (0-59)

getMonth() Get the month (0-11)

getSeconds() Get the seconds (0-59)

getTime() Get the time (milliseconds since January 1, 1970)

setDate() Set the day as a number (1-31)

setFullYear() Set the year (optionally month and day)

setHours() Set the hour (0-23)

setMilliseconds() Set the milliseconds (0-999)

setMinutes() Set the minutes (0-59)

setMonth() Set the month (0-11)

setSeconds() Set the seconds (0-59)

setTime() Set the time (milliseconds since January 1, 1970)

2015 @ Sonia Sousa 45

Page 46: Ifi7174 lesson3

JavaScript Output

• Display Possibilities

– window.alert()

– document.write()

– innerHTML

– console.log()

2015 @ Sonia Sousa 46

Page 47: Ifi7174 lesson3

window.alert()

• Is used to display data as a window alert

<script>

window.alert(5 + 6);

</script>

2015 @ Sonia Sousa 47

Page 48: Ifi7174 lesson3

document.write()

• For writing information in the document– Useful for testing purposes or to replace information

in a HTML page</script>document.write("<h2>“your name” </h2>");document.write("<img src='me.jpg' width='180'>");</script>

<p>My first paragraph.</p><button type="button" onclick="document.write(5 + 6)">Try it</button>

2015 @ Sonia Sousa 48

Page 49: Ifi7174 lesson3

innerHTML

• To access an HTML element by using

– the document.getElementById(id) method.

• id attribute defines the HTML element

• innerHTML property defines the HTML

<p>My First Paragraph</p>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML ="<h3>Welcome</h3>";

</script>

2015 @ Sonia Sousa 49

Page 50: Ifi7174 lesson3

JS and HTML

• Finding HTML elements

– by id

– by Tag Name

– by Class Name

• Changing elements in HTML

– Write in html

– HTML Content

– Value of an Attribute

document.getElementById("intro");

getElementsByTagName("p");

document.getElementsByClassName("intro");

document.write( );

document.getElementById("p1").innerHTML="New text!";

document.getElementById("image").src="landscape.jpg";

2015 @ Sonia Sousa 50

Page 51: Ifi7174 lesson3

JS and CSS

• Changing HTML Style

document.getElementById("p2").style.color="blue";

document.getElementById("p2"). background.color="blue";

document.getElementById("demo").innerHTML="<h3>Welcome</h3>";

2015 @ Sonia Sousa 51

Page 52: Ifi7174 lesson3

Js and events

• When an element is clicked on• Onclick

• onSubmit

– Or reacting to an event

• onmouseover and onmouseout

2015 @ Sonia Sousa 52

Page 53: Ifi7174 lesson3

Window Object MethodsMethod Description

alert() Displays an alert box with a message and an OK button

close() Closes the current window

confirm() Displays a dialog box with a message and an OK and a Cancel button

createPopup() Creates a pop-up window

moveBy() Moves a window relative to its current position

moveTo() Moves a window to the specified position

open() Opens a new browser window

print() Prints the content of the current window

prompt() Displays a dialog box that prompts the visitor for input

resizeBy() Resizes the window by the specified pixels

resizeTo() Resizes the window to the specified width and height

scroll() Deprecated. This method has been replaced by the scrollTo() method.

scrollBy() Scrolls the document by the specified number of pixels

scrollTo() Scrolls the document to the specified coordinates

stop() Stops the window from loading

2015 @ Sonia Sousa 53

Page 54: Ifi7174 lesson3

Conditionals

• If , if else, else if

– Execute the code if a specified condition is true

if (condition) {

block of code to be executed if the condition is true

} else {

block of code to be executed if the condition is false

}

2015 @ Sonia Sousa 54

Page 55: Ifi7174 lesson3

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

552015 @ Sonia Sousa

Page 56: Ifi7174 lesson3

Conditionals

• Switch – Case– perform different actions based on different

conditions.

switch ( expression )

{

case value1 :

statement-list1;

break;

case value2 :

statement-list2;

Break;

case ...

default:

break;

}

switch

andcase

are

reserved

words

If expression

matches value2,

control jumps

to here

2015 @ Sonia Sousa 56

Page 57: Ifi7174 lesson3

The For Loop

• to run the same code over and over again – each time with a different value.

for (statement 1; statement 2; statement 3) {code block to be executed

}– Statement 1

• is executed before the loop (the code block) starts.

– Statement 2• defines the condition for running the loop (the code block).

– Statement 3• is executed each time after the loop (the code block) has been

executed.

2015 @ Sonia Sousa 57

Page 58: Ifi7174 lesson3

Loops

var i;

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

document.getElementById("demo").innerHTML += i + "<br>";

}0123456789

2015 @ Sonia Sousa 58

Page 59: Ifi7174 lesson3

Conditionals

• Ifif (time<20)

{x="Good day";}

else{x="Good evening";}

function timegess(){var x="";var time=new Date().getHours();if (time<10)

{x="Good morning";}

else if (time<20){x="Good day";}

else{x="Good evening";}

}</script>

2015 @ Sonia Sousa 59

Page 60: Ifi7174 lesson3

Conditionals

• Switch - Case

– More than 1 condition

• select one of many blocks of code to be executed

switch(n){case 1:execute code block 1break;

case 2:execute code block 2break;

default:code to be executed if n is different from case 1 and

2}

switch (d){case 0:

x="Today it's Sunday";break;case 1:x="Today it's Monday";break;case 2:x="Today it's Tuesday";break;case 3:x="Today it's Wednesday";break;case 4:x="Today it's Thursday";break;case 5:x="Today it's Friday";break;case 6:x="Today it's Saturday";break;}

2015 @ Sonia Sousa 60

Page 61: Ifi7174 lesson3

JavaScript Form Validation

• A form can be validated using JavaScript function validateForm() {

var x = document.forms["myForm"]["fname"].value;if (x == null || x == "") {

alert("Name must be filled out");return false;

}}

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">

Name: <input type="text" name="fname"><input type="submit" value="Submit"></form>

2015 @ Sonia Sousa 61

Page 62: Ifi7174 lesson3

EXERCISE 3 – JAVASCRIPT

2015 @ Sonia Sousa 62