intro to javascript - eecs.yorku.cambrown/eecs1012/09-introjavascript.pdf · 2. write a javascript...

58
EECS1012 Net-centric Introduction to Computing M.S. Brown, EECS – York University 1 Lecture Introduction to Javascript EECS 1012 Acknowledgements Contents are adapted from web lectures for “Web Programming Step by Step”, by M. Stepp, J. Miller, and V. Kirst. Slides have been ported to PPT by Dr. Xenia Mountrouidou. These slides have been edited for EECS1012, York University. The contents of these slides may be modified and redistributed, please give appropriate credit. (Creative Commons) Michael S. Brown, 2017.

Upload: lephuc

Post on 14-Feb-2018

219 views

Category:

Documents


1 download

TRANSCRIPT

EECS1012Net-centric Introduction

to Computing

M.S. Brown, EECS – York University 1

Lecture

Introduction to Javascript

EECS 1012

Acknowledgements

Contents are adapted from web lectures for “Web Programming Step by Step”, by M. Stepp, J. Miller, and V. Kirst.

Slides have been ported to PPT by Dr. Xenia Mountrouidou.

These slides have been edited for EECS1012, York University.

The contents of these slides may be modified and redistributed, please give appropriate credit.

(Creative Commons) Michael S. Brown, 2017.

Intro to JavaScript (JS)2

Client-side scripting

EECS1012

3

JavaScript runs on the

browser (so we call this

"client side". JS provides a

way to dynamically modify

the HTML content and

appearance in the browser.

Why use client-side programming?

PHP already allows us to create dynamic web pages.

Why also use client-side scripting?

client-side scripting (JavaScript) benefits:

usability: can modify a page without having to post

back to the server (faster UI)

efficiency: can make small, quick (dynamic) changes to

page without waiting for server

event-driven: can respond to user actions like clicks and

key presses

EECS1012

4

EECS 1012

What is JavaScript?

a lightweight programming language ("scripting

language")

used to make web pages interactive

insert dynamic text into HTML (ex: user name)

react to events (ex: page load or user click)

can get information about a user's computer (ex:

browser type, history, etc)

perform calculations on user's computer (e.g.: for form

validation)

EECS1012

5

EECS 1012

JavaScript (JS) vs. Java

JS is interpreted, Java is compiled

JS has more relaxed syntax and rules

fewer and "looser" data types

variables don't need to be declared

errors often silent (few exceptions)

JS is contained within a web page and integrates

with its HTML/CSS content

EECS1012

6

EECS 1012

JavaScript vs. Java

EECS1012

7

+ =

EECS 1012

Interestingly, even though the name has "Java" in it, JavaScript

is not affiliated with Java (from Sun Microsystems – that is now

part of the Oracle Corporation).

(JavaScript is "mellow" version of Java)

JavaScript vs. PHP

differences:

JS focuses on user interfaces and interacting with a

document; PHP is geared toward HTML output and

file/form processing

JS code runs on the client's browser; PHP code runs

on the web server

EECS1012

8

EECS 1012

Linking to a JavaScript file: script

script tag should be placed in HTML page's head

script code is stored in a separate .js file

JS code can be placed directly in the HTML file's

body or head (like CSS)

but this is bad style (should separate content,

presentation, and behavior)

EECS1012

9

<script src="filename" type="text/javascript"></script>

HTML

EECS 1012

Event-driven programming10

EECS1012EECS 1012

Event-driven programming11

Event-driven programming: writing programs driven

by user events

Many programs (e.g. Java, C++, PHP) start when

the program is started.

JavaScript programs instead wait for user actions

called events and respond to them

EECS1012EECS 1012

An example: start with a button

button's text appears inside tag; can also contain

images

To make a responsive button or other UI control:

1. choose the control (e.g. button) and event (e.g. mouse

click) of interest

2. write a JavaScript function to run when the event

occurs

3. attach the function to the event on the control

EECS1012

12

<button>Click me!</button> HTML

EECS 1012

Your first JavaScript statement: alert

a JS command that pops up a dialog box with a

message

The appearance of the "alert" may look different

depending on the browser and operating systemEECS1012

13

alert("EECS1012 remains my favorite class!");

JS

EECS 1012

Defining a JavaScript function14

function functionName() {

statement ;

statement ;

...

statement ;

} JS

the above could be the contents of example.js

linked to our HTML page

statements placed into functions can be evaluated in

response to user events

function myFunction() {

alert("EECS1012 remains my favorite class!");

} JS

Event handlers in HTML

Linking HTML to JavaScript

JavaScript functions can be set as event handlers

when you interact with the element, the function will execute

onclick is just one of many event HTML attributes

we'll use

15

<element attributes onclick="function();">...

HTML

<button onclick="myFunction();">Click me!</button>

HTML

Putting it together

EECS1012

16

<!DOCTYPE html>

<html>

<head>

<script src="example.js" type="text/javascript"></script>

</head>

<body>

<button onclick="myFunction();"> Click Me! </button>

</body>

</html>

function myFunction() {

alert("EECS1012 remains my favorite class!");

}

HTML FILE

JS file: example.js

This statement

links in the JS file.

The JS file has

our JavaScript

code. Like CSS,

this is done by

file name.Event (click) of the HTML button,

calls the specified handler function

Effect of the previous code17

When this

button is

clicked, the

"alert" is

called from

the

function.

JavaScript Language18

JavaScript

EECS1012

19

If you are new to programming, you are going to

notice that many of the things you see in JavaScript

are almost the same as PHP

In fact, most programming languages are quite

similar and generally you can learn them quickly once

you have experience in another language

Variables

EECS1012

20

var clientName = "Connie Client";var age = 32; var id = 3994330;

Variables are defined by the keyword variable

Unlike PHP, we not need $ for the variable name

This may be confusing switching between PHP and JS

JS data types

EECS1012

21

TYPE Explanation Example

Number Integers and floats are not distinguished in Java

script

99, 2.8, 5, -10

String A variable that is a collection of characters. “Hello”, “EECS1012”

Boolean A variable that wholes only two possible values

– true or false.

true or false

Array A variable that is actually a collection of

variables that can be access with an index

[1,2,3,4, …]

[“hello”, “deaner”, …]

Objects Objects are special data types that have

functions and data associated with them. These

are more common in JS than PHP and we will

need to use them often.

Document.getElementByID();

(example of an object)

function A user defined function that can be called by an

user event (e.g. mouse click, etc)

function name (){statements;..}

Number type

EECS1012

22

var enrollment = 99; var medianGrade = 2.8; var credits = 5 + 4 + (2 * 3);

same operators at PHP:

+ - * / % ++ -- += -= *= /= %=

same order of precedence as PHP

auto converts strings to number like PHP

"2" * 3 = 6

String type

EECS1012

23

var s = "Connie Client"; var len = s.length; // 13var s2 = 'Melvin Merchant';

Like PHP, strings can be specified with both " and '

Unlike, PHP, variables are not interpreted in ""

There is a built in property .length that returns the

string length

Object property access

EECS1012

24

var s = "Connie Client"; var len = s.length;

variable s is of

type String, however,

this can also be thought

of as a "String object".

we can access various properties

of the object using a "." and the

property's name. You are going

to see this type of property access

often in JavaScript (and other "Object

Oriented" languages)

String concatenation (+ operator) 25

var s1 = "Hello ";var s2 = "World \n";var s3 = s1 + s3; // s3 = "Hello World \n";

The plus operator is used for string concatenation

There is no . operator for strings like PHP

The . operator will be used for accessing objects

data. For example, previous slide: s.length was

the length of a string.

The escape sequences are similar to PHP

\n, \", \'

JavaScript Access to the HTML page

EECS1012

26

JavaScript Functions

Define functions that are called

when events occur on the HTML

page in the browser.

JS needs a mechanism to access

the HTML document's structure.

The solution:

Document Object Model (DOM)

HTML consists of elements. Now that you

have learned forms, you know some elements

can generated events (like data input & button clicks)

JavaScript adds the ability to

attach code that response to HTML

events. It also needs a mechanism

to access the HTML elements.

DOM

Document Object Model (DOM)

most JS code manipulates

elements on an HTML page

we can examine elements'

"state"

e.g. see whether a box is

checked

we can change state

e.g. insert some new text into

a div

we can change styles

e.g. make a paragraph red

27

DOM element objects28

Object function call syntax

EECS1012

29

document.getElementById("id")

Object "document" Call the object's function (also called a method)

getElementByID( . . .)

DOM element properties30

EECS1012

Property Type Description

className stringThe class attribute of the element ("" if no class is

set)

id stringThe id attribute of the element (undefined if no id is

set)

innerHTML string

The HTML markup and content inside the element, i.e.

between its opening and close tags ("" if there is no

content)

style stringAn object representing the elements style attributes (see

slide X)

tagName stringThe element's HTML tag, in uppercase (e.g. "P", "DIV",

"H1", "SPAN", etc)

EECS 1012

Additional DOM properties31

EECS1012

Property Type Description

checked boolean whether a checkbox or radio button is checked

disabled boolean Whether a form control is disabled

href string The URL for a link (a)

src string Source URL for an image (img)

value stringText inside a form control such as an input or

textarea

EECS 1012

Accessing elements: document.getElementById

32

document.getElementById() returns the DOM object

for an element with a given id

can change the text inside most elements by setting

the innerHTML property

can change the text in form controls by setting the

value property

EECS1012EECS 1012

Example

EECS1012

33

<html>

<head>

<script src="replaceText.js" type="text/javascript"></script>

</head>

<body>

<button onclick="changeText();">Click me!</button>

<p id="myText"> Replace this text </p>

</body>

</html>

function changeText() {

var paragraph = document.getElementById("myText");

paragraph.innerHTML = "Changed the text with JS!";

}

replaceText.js

replaceText.html

<body>

<button onclick="changeText();">Click me!</button>

<p id="myText"> Replace this text </p>

</body>

function changeText() {

var paragraph = document.getElementById("myText");

paragraph.innerHTML = "Changed the text with JS!";

}

JS program breakdown

EECS1012

34

(1) Creates a button,

links click event to JS function changeText() (1)

(2)

(2) Creates a paragraph with ID

myText. You have seen this with CSS before.

When the event happens . this code is executed.

(1) Retrieves the element by ID name "myText"

(2) Changes its innerHTML data property.

(1)

(2)

Browser Output

Browser Output

Accessing elements: document.getElementById

35

Previous example showed how to change the

"innerHTML" property

We can also change the style properties of the

HTML element using JavaScript

EECS1012EECS 1012

Changing element style: element.style

36

EECS1012

CSS Attribute DOM Property / style object

color color

padding padding

background-color backgroundColor

border-top-width borderTopWidth

Font size fontSize

Font famiy fontFamily

EECS 1012

Example

EECS1012

37

<html>

<head>

<script src="example2.js" type="text/javascript"></script>

</head>

<body>

<button onclick="changeText();">Change Style!</button>

<span id="output">replace me</span>

<input id="textbox" type="text">

</body>

</html>

function changeText() {

var text = document.getElementById("textbox");

text.style.color = "blue"; /* Changes style color to blue */

text.style.fontSize = "3em"; /* Changes style fontSize to 3em */

text.style.fontFamily = "monospace"; /* Changes fontFamily to monospace */

}

changeStyle.js

changeStyle.html

EECS1012

38

Result from previous slide

After clicking button.

function changeText() {

var text = document.getElementById("textbox");

text.style.color = "blue";

text.style.fontSize = "3em";

text.style.fontFamily = "monospace";

}

<input id="textbox" type="text">

The input field id name is "textbox".

We retrieve this element using

the DOM getElementById().

Change the style

More Javascript Syntax39

Comments (same as Java)

identical to Java's comment syntax

recall: 4 comment syntaxes

HTML: <!-- comment -->

CSS/JS/PHP: /* comment */

Java/JS/PHP: // comment

PHP: # comment

EECS1012

40

// single-line comment

/* multi-line comment */

JS

EECS 1012

More on JS string type41

var count = 10;var s1 = "" + count; // "10"var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah ah ah!"var n1 = parseInt("42 is the answer"); // 42 Numbervar n2 = parseFloat("3.403 is a test"); // 3.403 Number

Concatenation with an empty string is a quick way to

convert a variable to a string (see var s1 example)

Unlike PHP, if we want to convert a string to a number,

we have to use a function

parseInt() /* means parse Integer*/

parseFloat() /* means parse Float */

Yet more on JS string type

EECS1012

42

var s = "a string";var firstLetter = s[0]; // fails in IEvar firstLetter = s.charAt(0); // does work in IEvar lastLetter = s.charAt(s.length - 1);

One drawback of JavaScript is that it is not

standardized across browsers

Accessing characters in a string works like PHP for

some browsers, e.g.

s[0], s[1], s[2], . . .

We can to use the s.charAt(index) method.

s.charAt(0), s.charAt(1), s.charAt(2)

Special values: null and undefined43

var ned = null;

var benson = 9;

// at this point in the code,

// ned is null

// benson's 9

// caroline is undefined

JS

EECS1012

undefined : has not been declared, does not

exist

null : exists, but was specifically assigned an

empty or null value

Why does JavaScript have both of these?EECS 1012

Logical operators – same as PHP44

EECS1012

> < >= <= && || ! == != === !==

most logical operators automatically convert types:

5 < "7" is true

42 == 42.0 is true

"5.0" == 5 is true

=== and !== are strict equality tests; checks both

type and value

"5.0" === 5 is false

EECS 1012

if/else statement (same as PHP)45

if (condition) {

statements;

} else if (condition) {

statements;

} else {

statements;

}

JS

EECS1012

identical structure to Java's if/else statement

JavaScript allows almost anything as a condition

EECS 1012

Boolean type46

var iLike190M = true;

var ieIsGood = "IE6" > 0; // false

if ("web devevelopment is great") { /* true */ }

if (0) { /* false */ }

JS

EECS1012

any value can be used as a Boolean

"falsey" values: 0, 0.0, NaN, "", null, and undefined

"truthy" values: anything else

converting a value into a Boolean explicitly:

var boolValue = Boolean(otherValue);

var boolValue = !!(otherValue);

EECS 1012

for-loop (same as PHP andJava)47

var sum = 0;

for (var i = 0; i < 100; i++) {

sum = sum + i;

} JS

var s1 = "hello";

var s2 = "";

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

s2 += s1.charAt(i) + s1.charAt(i);

}

// s2 stores "hheelllloo" JS

EECS1012EECS 1012

while loops (same as PHP) 48

while (condition) {

statements;

} JS

EECS1012EECS 1012

var i=0;

var sum = 0;

while (i < 100) { /* loops whie i is less than 100

*/

sum = sum + i; /* adds up 0 to 99 */

i++; /* adds one to I */

} JS

Example – only difference from PHP is in the JS variable syntax.

Popup boxes49

alert("message"); // message

confirm("message"); // returns true or false

prompt("message"); // returns user input string

JS

EECS1012EECS 1012

Arrays50

var name = []; // empty array

var name = [value, value, ..., value]; // pre-filled

name[index] = value; // store element

JS

EECS1012

var ducks = ["Huey", "Dewey", "Louie"];

var stooges = []; // stooges.length is 0

stooges[0] = "Larry"; // stooges.length is 1

stooges[1] = "Moe"; // stooges.length is 2

stooges[4] = "Curly"; // stooges.length is 5

stooges[4] = "Shemp"; // stooges.length is 5

JS

EECS 1012

Finish with another example (ver 1)

EECS1012

51

<html>

<head> <script src="add.js" type="text/javascript"></script> </head>

<body>

<h1>The Amazing Adder</h1>

<div>

<input id="num1" type="text" size="3"> +

<input id="num2" type="text" size="3"> =

<span id="answer"></span> <br>

<button onclick="compute();">Compute!</button>

</div>

</body>

</html> function compute() {

var input1 = document.getElementById("num1");

var input2 = document.getElementById("num2");

var answer = document.getElementById("answer");

var result = input1.value + input2.value;

answer.innerHTML = result;

}

add.html

add.js

Finish with another example (ver 1)

EECS1012

52

<input id="num1" type="text" size="3"> +

<input id="num2" type="text" size="3"> =

<span id="answer"></span> <br>

<button onclick="compute();">Compute!</button>

function compute() {

var input1 = document.getElementById("num1");

var input2 = document.getElementById("num2");

var answer = document.getElementById("answer");

var result = input1.value + input2.value;

answer.innerHTML = result;

}

There is an empty

span here with

id=answer

Placed the results

in the span elements

"innerHTML"

The uses the DOM to get the elements.

input1 and input2 are <input> so to access their

data we use ".value". answer is a <span> so to

change its value we use "innerHTML"

But wait?

EECS1012

53

function compute() {

var input1 = document.getElementById("num1");

var input2 = document.getElementById("num2");

var answer = document.getElementById("answer");

var result = input1.value + input2.value;

answer.innerHTML = result;

}

Why is the answer "1010"? Because input1.value="10" and input2.value="10",

are strings. So, "10" + "10" in JavaScript is "1010", because + is the concatenation

operator.

If we want to convert these, we need to use the function parseInt( );

Finish with another example (ver 2)

EECS1012

54

<input id="num1" type="text" size="3"> +

<input id="num2" type="text" size="3"> =

<span id="answer"></span> <br>

<button onclick="compute();">Compute!</button>

function compute() {

var input1 = document.getElementById("num1");

var input2 = document.getElementById("num2");

var answer = document.getElementById("answer");

var result = parseInt(input1.value) + parseInt(input2.value);

answer.innerHTML = result;

}

We only need to

modify the JS code.

One more example . . .

EECS1012

55

var i = 1;

function changeImage() {

var foodimage = document.getElementById("food");

var images = ["dosa.jpg", "falafel.jpg", "pide.jpg", "malaxiangguo.jpg"];

foodimage.src = images[i];

i++;

if (i > 3) { i = 0; }

}

<!DOCTYPE html>

<html>

<head>

<script src="example3.js" type="text/javascript"></script>

</head>

<body>

<p> Click image to see some of my favorite foods:

<img onclick="changeImage();" src="dosa.jpg" height="100" id="food"></p>

</body>

</html>

example3.js

example3.html

Previous JS example

Attaches code to an "onclick" event for an image!

Events do not have to be only for buttons!

When the image is clicked, the code gets the

image's element using the DOM and changes the

images source

An array of four images is used to store the image

names

A "global" variable is declared (outside the

function) that keeps its value between function calls

EECS1012

56

Result of previous code

EECS1012

57

Each time you click the image, the

image changes!

Recap

This lecture has introduced you to JavaScript

The language is similar to PHP, however, variables

syntax are different (no need for the $)

Other differences with strings, arrays, etc. . but overall

quite similar

JS is also more object-oriented, so we have more

object notation, e.g. var.innerHTML,

var.style.color, etc.

JS is also "event" driven, which we will explore

more in coming lecturesEECS1012

58