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

20_Programming for the Web

Chapter 20 covers essential JavaScript concepts including data types, variables, functions, and control structures to create interactive web pages. It explains how to use arrays, conditional statements, loops, and event handling to enhance user interaction. The chapter also provides practical examples and exercises to reinforce learning of JavaScript programming techniques.

Uploaded by

szelin.lee
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

20_Programming for the Web

Chapter 20 covers essential JavaScript concepts including data types, variables, functions, and control structures to create interactive web pages. It explains how to use arrays, conditional statements, loops, and event handling to enhance user interaction. The chapter also provides practical examples and exercises to reinforce learning of JavaScript programming techniques.

Uploaded by

szelin.lee
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Programming for the Web

Chapter 20
Learning Objectives

• demonstrate a range of object-based


 recognise data types (including number, string, Boolean, array, object)
 assign and understand the term variables
 carry out calculations and basic string manipulation
 use arrays
 use comparison and logical operators
 use conditional statements (including if, else, else if, switch)
 use loops (including for, for/in, while, do/while)
 use iterative methods
 create functions
 trap errors
 control events
 create html forms to interact with the user
 add comments to explain JavaScript code

• add interactivity to webpages


• explain JavaScript terms and programming techniques
Key terms

Word/ Meaning
phrase
alert Displays a box containing a message to the user / containing results
array Arrays are indicated by square brackets and are used to store multiple values in a
single variable, each of which can be accessed by referring to an index number. Array
items are separated by commas.
bookmark An identifier put into the body of the html code to specify where script results are
placed in the webpage
Boolean Booleans can only have either of two values: true or false.
conditional Allows a program to perform different actions depending on the result of a condition;
statement the most commonly used are: if, if…else, if…else if, switch
confirm Displays a box that the user needs to click to continue / cancel
function A block of code designed to perform a particular task that can be called anywhere in
a script, and any number of times
Key terms

Word/ Meaning
phrase
global Variable that can be used in functions other than the function in which it is declared
variable or other parts of the script
local variable Variable available only within the function in which it is declared
loop Repeats a task until a certain condition is met; the most commonly used are: while,
statement do…while, for, for…in
number Numbers are one of JavaScript data types. They can be written with or without
decimals, and can use scientific notation for extra large or extra small numbers.
object Objects are indicated by curly brackets and are containers for properties called
named values. For example an object such as a blue bicycle would have a named
value of colour:”blue”. An objects properties use the following convention -
name:value, name:value, name:value, etc.
operator Symbol that indicates a specific process: arithmetic, string,
assignment, comparison, logical, or conditional
Key terms

Word/ Meaning
phrase
pop-up Alert, Prompt, Confirm boxes
prompt Dialog box that asks the user for input and assigns the input to a variable
script A high-level programming language (set of instructions), such as JavaScript that is
‘interpreted’ rather than compiled (e.g. when a web page is displayed)
string A string is text like a letter, word or phrase. Strings are indicated by quote marks and
either single or double quote marks can be used. Quote marks can be used within a
string, but they mustn’t match the quote marks that surround the string.
variable Named container to which data is assigned; can contain the following data types: text
(strings), number, boolean, array, object
Introduction

• When accessing websites, we are interacting with <html>


them by clicking buttons, entering data and <body>
selecting from lists of options. This is my first web page

• JavaScript is the scripting language (supported by <script>


major web browsers) that is primarily used for alert("Hello World!");
creating interactive features on webpages. </script>
</body>
• JavaScript is written within the HTML code of a </html>
webpage and the HTML code then calls this
JavaScript code.

• JavaScript adds additional content to the webpages


to make them perform more actions and engage
the user.
JavaScript (Part 1)

1. document.write() will output the text (content) inside the bracket to the web
page.
[Pg. 470, Worked Example 20.01]

2. .innerHTML is used when you need to name elements within your HTML code
and use script tag to instruct JavaScript to add the text to the document in the
element with the specific ID.
[Pg. 471, Worked Example 20.02]

3. Pop-up boxes (alert, confirm, prompt) can be used to display text or


information that appears in an extra box on top of the screen.
[Pg. 472, Worked Example 20.03]

4. console.log is used to make your web page record events, write messages to
etc. that do not actually appear on the web page, but appear in a log, which is
JavaScript (Part 1)

5. Changing images
[Page 475, Practical Activity 20.4]

6. Changing HTML style (font colour/style, background colour of text, etc.)


[Page 476, Worked Example 20.05]

Homework ** [Page 478, Practical Activity 20.06, Question 2] **


JavaScript (Part 2) – Variables, Operators and
Functions

1. A variable is a space in memory that is given a name


1. (an identifier),
A variable where in
is a space you can store
memory thatdata that can
is given a name (an identifier), where you can
change while
store data thatthe program
can changeiswhile
running.
the program is running.

2. Identifier naming
namingrules
rules are:
are:
 can contain alphabets, numbers or underscore (_) but do not start with number or
but
underscore.
 must not contain space; can join together multiple words, using lower case for the
whole first word and then capitalize subsequent words.
 make variable names intuitive/meaningful, so they describe the data they contain.
 variables are case sensitive, for example, myage is a different variable
from myAge.
 avoid using JavaScript reserved words, for example var, function, let, and for.
 clovis
 Clovis
 aileenNatasha
 aileennatasha
 clovis_wong
 clovis_Wong
 thisIsAGoodDay
JavaScript (Part 2) – Variables, Operators and
Functions

3. A variable declaration refers to the statement that tells the program that you need
a space in memory and what its identifier will be. For example, var name;
4. An assignment operator (=) adds a value to a variable.
For example:
name = “Lee”;
age = 17;
isSold = True;

5. The data stored in a variable will be of a set of data type. For example, String,
Number, Boolean, Array, Object.
* var name;
var name = ‘Lee’;
Data types are not declared when declaring a variable, it is assumed when a
value is given/assign to the variable.
JavaScript (Part 2) – Variables, Operators and
Functions

6. Type conversion:
a) to String
var stringNumber = String(999);

b) to integer
var numberString = Number(“999”);

c) Boolean to number
var numberBoolean = Number(true);

+ symbol: addition OR join together two strings.

[Page 479, Worked Example 20.06]


JavaScript (Part 2) – Variables, Operators and
Functions

7. Arithmetic Operators (+, -, *, /, ++, --, %, floor() )


[Page 481, Worked Example 20.07]
[Page 482, Practical Activity 20.08, Q1, Q4]

8. Function is:
 a set of instructions that perform a specific task.
 independent code that only runs if it is called.
 very useful for removing repeated code, especially when it may need to be
repeated at different positions/locations in a program.
• Functions can be:
 called from within the JavaScript code
 called when an event occurs such as clicking a button
 automatically run (self-invoked).

[Page 482, Worked Example 20.08];


JavaScript (Part 2) – Variables, Operators and
Functions

• A function can take values from the program that calls it; these are called
parameters. It can also return a value back to the program that called it.

[Page 483, Worked Example 20.09]


[Page 483, Practical Activity 20.09]

• When a function is being created, variable(s) can be created locally (inside the
function) or globally (outside of the function).
 A local variable exists only when the function is running; it can only be
accessed (e.g. output or changed) from within the function.
 A global variable exists as soon as the web page loads, and permanently
exists;
it can be accessed anywhere within the JavaScript.
JavaScript (Part 3) – Form elements

9. All the code to display buttons, drop-down boxes etc. comes within the
<form></form> tag.

a) button
When user clicks on a HTML button, it can be programmed to call a JavaScript
function.

<button onclick = “outputMessage()”>Click me</button>

[Page 485, Worked Example 20.10]

[Page 486, Practical Activity 20.11, Q1, Q2]


JavaScript (Part 3) – Form elements

9. All the code to display buttons, drop-down boxes etc. comes within the
<form></form> tag.

b) text box
You can enter text into a text box, and then access the data and use it.

<input type=“text” id=“enterColour”>

An action is needed to tell JavaScript to get the data from the text box.

[Page 486, Worked Example 20.11]

[Page 487, Practical Activity 20.12, Q2]


JavaScript (Part 3) – Form elements

9. All the code to display buttons, drop-down boxes etc. comes within the
<form></form> tag.

c) drop-down box
It gives the user options to choose from.

d) radio button
It gives the user a range of options that they can see, but can only select
one.

[Page 488, Worked Example 20.12]

[Page 492, Practical Activity 20.14, Q3]


JavaScript (Part 4) – Detecting events

10.Detecting events

a) onload - When attach to an element, it will run when the element is called or
loaded.

b) onchange – Can be attached to an element that the user can change, e.g. drop-
down box.

c) onmouseover – will run when user moves the cursor over an element, e.g. an
image.

d) onmouseout – will run when the user moves the cursor away from an element,
e.g. an image.

e) onkeydown – will run when user interact with a text box, e.g. clicks a key on the
keyboard.
JavaScript (Part 5) – Show and hide HTML
elements

HTML elements (e.g. paragraphs) can be made visible (appear on screen), and invisible
(cannot be seen)

document.getElementById(“text1”).style.visibility = “hidden”;
document.getElementById(“text1”).style.visibility = “visible”;

OR

document.getElementById(“text1”).style.display = “none”;
document.getElementById(“text1”).style.display = “inline”;

[Page 493, Worked Example 20.13]

[Page 494, Practical Activity 20.14, Q2]


JavaScript (Part 6) – Conditional Statements
(Selection)

• A conditional statement allows a program to perform different actions depending on the result of a
condition: a different block of code is run for each decision branch.

• There are four commonly used conditional statements:


1. if – specifies a block of code to be executed, if a required condition is true

if (some condition is true) {


do something;
}

2. if ... else – allows the program to run an alternative block of code if the condition is not met.

if (some condition is true) {


do something;
} else {
do something else;
}
JavaScript (Part 6) – Conditional Statements
(Selection)

• A conditional statement allows a program to perform different actions depending on the result of a
condition: a different block of code is run for each decision branch.

• There are four commonly used conditional statements:


3. if ... else if – an extended form of if...else that allows the program to make a correct decision out of
several conditions; if none of the conditions is true, then the final “else” block is executed as a form
of error trapping.

4. switch – is used to select one of many blocks of code to be executed, depending on the value of a
variable; if nothing matches, a default condition will be used.
switch (resulting value of a variable) {
case condition 1:
statement(s);
break;
case condition 2:
statement(s);
break;
default:
statement(s);
}
JavaScript (Part 6) – Conditional Statements

Activity/Homework:

[20.12 Selection: Worked Example 20.14, Worked Example 20.15, Questions (Page
499)]
JavaScript (Part 6) – Conditional Statements

• Ternary operator – a short-hand if... else which can be used to replace multiple lines
of code with a single line.

var variable = (condition) ? expressionTrue : expressionFalse;

instead of:

if (condition is true) {
expressionTrue;
} else {
expressionFalse;
}

[Practical Activity 20.16, Q1, Q2, Q3, Q4, Q6]


JavaScript (Part 7) – Arrays

• It is a data structure that allows you to store multiple values (of the same data type)
under one name.

• For example, an array of colours with five elements.


Index 0 1 2 3 4

Value orange purple green yellow grey

var colours = [“orange”, “purple”, “green”, “yellow”, grey”];


var myFavColour – colours[2];
colours[1] = “pink”;
colours.push(“blue”);
var arrayLength = colours.length;

[Page 500, Worked Example 20.16; Practical Activity 20.18 – Q3]


JavaScript (Part 8) –
Loops/Repetitions/Iterations

• It is a construct that repeats the code inside it a number of times based on a


condition.

• A loop is used when you want to perform the same action multiple times.

• There are two types of loop: count controlled (for) and condition controlled
(while and do/while)

• for: you need to know the number of times the loop is to run.

for (count = 1; count <=12; count++){


alert (count*count);
} //
this for loop will output 12 square numbers
JavaScript (Part 8) –
Loops/Repetitions/Iterations

• for/in: it is used if you have a JavaScript object that you need to repeat through
each element to output them all.
var film = {title:”The house”, genre:”Drama”, length:96, releaseYear:2013};
var count;

for (count in film){


document.write(filem[count]);
} //this code
will output each of the elements within the object.

[Page 503, Worked Example 20.17]

[Page 505, Worked Example 20.19, Q1, Q4]


JavaScript (Part 8) –
Loops/Repetitions/Iterations

• while: runs the code while a condition is true.


var count = 0;
while (count<=12){
document.write(count*count)
count++;
} //this code
will display 12 square numbers.

var check=true;
while (check=true){
document.write(“It’s true”)
} //this while
loop does not use a counter.
JavaScript (Part 8) –
Loops/Repetitions/Iterations

• do/while: checks at the end of the loop; it will run at least once.
var count = 0;
do{
document.write(count*count)
count++;
}
while(count<=12);

[Page 505, Practical Activity 20.19, Q2]

[Practical Skills Task 1]


JavaScript (Part 9) – Timing events

• setTimeout – allows to set a delay before something happens.

setTimeout(function(){
prompt(“Do you want to continue?”);
}, 2000);

• setInterval – allows to make something happen repeatedly for a period of time.

setInterval(function(){
alert(“Hello”);
}, 1000);

[Worked Example 20.18, Worked Example 20.19, Practical Activity 20.20 – Q2,
Q4]
[Practical Skills Task 7, Practical Skills Task 6]
JavaScript (Part 10) – String manipulation

• Allows you to perform actions on a string and extract information from it.

• When counting letters in a string, the first letter is letter 0, and the second is letter
1,
the third is letter 2, and so on.

• Spaces and all symbols are all counted as letters.

[Worked Example 20.20, Practical Activity 20.22, Q1, Q2, Q3]


JavaScript (Part 11) – Iterative methods

• It is a function that is repeated, for example, applied to each element in an array.

1. every
2. some
3. filter
4. forEach
5. map

[Worked Example 20.21, Practical Activity 20.24, Q1]


JavaScript (Part 12) – Trap errors

• Errors can occur in a variety of places in a program and for a variety reasons.

• To trap these error, try and catch code is used.


try {
tryCode //Code block to run
}
catch(err) {
catchCode //Code block to handle errors
}
finally {
finallyCode //Code block to be executed regardless of the try result
}

[Practical Activity 20.25, Q1,Q2]


JavaScript (Part 13) – Using external scripts

• Write the JavaScript in a separate document and then import into the HTML
document.
 create a separate document and write the JavaScript code inside.
 save the file with a name and the extension .js
 call the code within the HTML document.
<html>
<script src=“javascriptparagraph.js”></script>
<html>

[Practical Activity 20.26]

[Practical Skills Task 2, Practical Skills Task 3)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy