Programming For The Web
Programming For The Web
CONTENT
Introduction to JavaScript
Outputting data
Pop-up boxes
Changing images
Changing HTML styles
Variables and operators
Arithmetic operators
Functions
Form elements/controls
Detecting events
Showing and hiding HTML elements
Selection
Arrays
Loops
Timing events
String manipulation
Comments
Iterative methods
Trap errors
Using external scripts
Introduction
JavaScript is used to enhance and add user interactivity to websites.
Website interaction includes clicking buttons, entering data, and selecting from sets of
options.
JavaScript is a scripting language used to add interactivity to web pages.
JavaScript is written within the HTML code of a web page and the HTML code then calls this
code.
JavaScript, which is a front-end scripting language, can be integrated with other back-end
languages such as PHP to allow your website to communicate with a database stored on the
web server.
JavaScript adds additional content to webpages to perform more actions and engage the
user.
Importance of JavaScript
It adds additional content to webpages which makes them perform more actions.
It makes webpages engage the user.
Gives the web developer more control over the webpage content.
1
Allows a website to communicate with a database stored on the web server.
INTRODUCTION TO JAVASCRIPT
JavaScript keywords/reserved words are words with a special meaning used to tell the
webpage what to do.
JavaScript can be added to an HTML document.
JavaScript code is started and ended within script tags (<script>…</script>).
Example 1
2
NB Code indentation makes the code easier to read. It shows limits of code structures for
tags above, selection and looping structures. E.g. indentation reduces chances of missing
tags above.
OUTPUTTING DATA
There are different ways/methods to output data in a JavaScript program.
document.write()
innerHTML
alert
1. document. write
document.write(theOutput) ; will output the text inside the brackets to the webpage.
Its output will overwrite all other HTML content including headings, paragraphs, buttons
etc.
Example
3
Example 20.01
Create a webpage that displays the title: “My First JavaScript Web Page”, at the top of the
page.
NB The text inside brackets is in speech marks because it is a string. If speech marks are
missing, then the webpage regards the text as variables which will be meaningless.
Open the HTML file in a browser to see the result of this code.
String- a data type where data is stored as text such as characters, numbers and symbols.
2. .innerHTML
HTML code elements can be named and thus be given IDs.
For e.g., to name the first paragraph in your website to paragraph1:
<p id=“paragraph1”>….</p> OR
<p ID=“paragraph1”>….</p>
4
To instruct JavaScript to add some text to the HTML document, within the script tags, in the
element with ID paragraph1:
Example 20.02
Create a webpage with two paragraphs and with different text in each paragraph. The
paragraphs are declared with IDs paragraph1 and paragraph2.
POP-UP BOXES
5
Used to display text/information in an extra box on top of the screen.
There are three types of pop-up boxes:
alert
confirm
prompt
alert
Displays text in a box over the top of a webpage.
Usually to alert the user of something.
E.g.: Below statement will display the text “Hello World” in an alert box.
confirm
A confirm box has two options: OK and Cancel
E.g.: This confirm box will display “OK to proceed?”
confirm(“OK to proceed?”);
The option chosen by the user is returned as a Boolean value that can be used to decide
what to do in code.
If user clicks OK, then true is returned.
If user clicks Cancel, then false is returned.
E.g.: In below example, the value returned is stored in the variable answer.
prompt
A prompt box allows a user to enter some text and gives them the option of OK and Cancel.
If OK is selected, then the text input can be stored in a variable e.g., its stored in a variable
answer below:
6
console.log
Used to view console mode of a webpage for debugging purposes.
The console output is not meant for regular users like normal webpage content but is meant
for programmers to debug the erroneous code.
Normal webpage content display in the normal browser window while console output
displays in the special console window of the browser.
Console mode is used to make a webpage record events, write messages to, etc. that do not
actually appear on the webpage but rather appear on a log.
To view console mode, open your browser with the webpage on and press F12- a tab with
console on it will appear OR look for the Developer Tools or simply Tools menu in major
browsers.
If using Chrome, press Ctrl+Shift+J
If using Firefox, press Ctrl+Shift+I
Click on the Console menu option to view the console log.
Example
To check if JavaScript has gone into a selection/IF statement, output a unique message to
the log to confirm the script has run, include below statement within the body of the IF
structure:
console.log(“in IF statement”);
If message “in IF statement” does not appear in the log, then you know that statements
within the if statement are not being executed and hence you know where to start looking
for the error.
7
Example 20.03
Create a webpage that:
Firstly, displays an alert welcoming you to the website.
Secondly, asks you to confirm that you want to proceed to the question.
Thirdly, asks a question where you must type an answer.
At each stage it must write a log to the console to say what it has done.
Open the website with the console log open and watch what happens.
8
CHANGING IMAGES
An HTML image can be set or changed using the document.getElementById command.
Make sure the HTML code for your image/image placeholder has an ID.
Example
<img src=”” id=”firstImage”>
document.getElementById(“firstImage”).src=”SS1.jpg”;
In above code, the HTML image element will display the image with the name “SS1.jpg” that
is saved in the same folder as the webpage file.
9
Other image properties can be accessed and changed using the same
document.getElementById command-simply change the .src to the property you want to
edit.
document.getElementById(“image1”).height=”500”;
document.getElementById(“image1”).width=”500”;
Example 20.04
Create a webpage with the title “My Images”, and then two images underneath that are
set using JavaScript.
10
CHANGING HTML STYLES
Different properties of HTML elements can be changed in JavaScript using the
document.ElementById command such as colour and style of font, background colour of a
section of text etc.
Examples
1. document. getElementById(“p1”).style.color=”red”;
2. document. getElementById(“p1”).style.fontSize=”xx-large”;
11
3. document. getElementById(“p1”).style.backGroundColor=”blue”;
Example 20.05
Create a website that has two paragraphs of text. Use JavaScript to make the first
paragraph in:
Purple
Arial font
Size small
12
Example
Below code sets both the font family and the borderstyle of an HTML paragraph to solid
directly in HTML.
13
VARIABLES AND OPERATORS
Variable
An address/space in computer memory that is given a name/identifier where data can be
stored.
The value of a variable can change while the program is running.
Example
A variable called name could be declared and the text value “Luca” stored in it. This value
could later be changed in the program to the text value “Katerina”.
14
Must be one word i.e. no spaces are allowed e.g.:
name
FirstName
firstName
country_name
Must start with a letter.
Must not be a JavaScript reserved/key word e.g. True, var, alert, etc.
Must be meaningful i.e. its name suggests its purpose.
Can only consists of letters, numbers and the underscore character.
Declaration
Declaration is a program statement that gives the identifier/name of a variable or array
using the var or let key word.
E.g.:
var name; //this tells JavaScript that you are creating a variable with name “name”.
var num1, num2, num3; //several variables can be declared on the same line.
Constants
These are identifiers whose values cannot change after being set.
They are declared using the const key word instead of var key word e.g.:
const pi=3.141519;
Assignment
It is storing a data value in a variable.
E.g.:
name=”Luca”; //where name is a variable name, = is the assignment operator, Luca is a
string value.
age=18; //where age is a variable name, = is the assignment operator, 18 is an integer
value.
The values in the above variables can be changed as below and thus overwrites the previous
data.
name=”Moses”;
age=82;
Data types
15
The data stored in a variable will be of a set data type and JavaScript assigns the data type
to a variable depending on the data value stored in it.
16
NB Data types are not assigned when a variable is declared. Rather, the data type is
assumed/decided by JavaScript when a value is given to the variable.
Example
var name; //name could be of any data type.
name= “”; //name is now a string.
var age; //age could be of any data type.
age=0; //age is now a number.
A Boolean is a data type that holds the value either true or false.
17
Examples
1. To convert a number or Boolean value to a string, use the String() function.
Eg.:
var stringNumber=String(999);
var stringBoolean=String(true);
Example 20.06
Create a webpage that stores the first name, last name, and age of a person in variables.
The script should then output all the information in separate alerts.
18
ARITHMETIC (MATH) OPERATORS
Operator
It is a symbol/set of symbols that perform a specific operation e.g. arithmetic operators.
There are three key types of operators in JavaScript:
Arithmetic operator
Comparison operator
Logical operator
Arithmetic operator
A symbol/symbols that perform a mathematical calculation e.g. + , - , /, *, ^, etc.
Comparison operator
A symbol/symbols that compare the two sides of the operator and produces a Boolean
result e.g. ==, !=, <, >= etc.
Logical operator
A symbol that represents the logical operations AND, OR and NOT.
19
Literal/constant data value
The actual data value being used instead of a variable e.g. 18, “Mary”, true, 198.23 etc.
20
NB An arithmetic calculation can use numbers (literals/constants), variables or both.
21
Examples
1. x=5;
x++; //increases by 1 i.e. x=x+1=6
2. x=5;
x-- ; //decreases by 1 i.e. x=x-1=4
3. x=5;
x+=4 ; //adds to itself x=x+4=9
4. x=5;
x-=4; //subtracts from itself x=x-4=1
Example 20.07
Create a webpage that stores 9999 and 1000 in variables, and then calculates and outputs
the result of:
9999+ 1000
9999- 1000
9999* 1000
9999% 1000
floor(9999/1000)
22
23
FUNCTIONS
Function
A named set of instructions that perform a specific task.
It is independent code that only runs if it is called.
Functions remove repeated code which may need to be repeated at different positions in
the program.
Instead of rewriting the code, simply call the function.
Rewriting the code gives more opportunity for error.
24
A function must first be declared/defined in JavaScript and then called either before or after
the function’s declaration.
Example
<script>
function outputNums () {
document.write(0);
document.write(1);
};
</script>
<script>
…
outputNums();
…
</script>
Example 20.08
Create a program that has a function to output “Hello World”.
Parameters
These are input values accepted by a function from the calling program and uses them
within its body.
A function may or may not accept parameters depending on its purpose.
A function may also return a data value/result to the calling program.
25
Example
function addNums(num1, num2) {
return num1+num2;
}
The above function addNums takes two numbers/parameters, num1 and num2, adds these
together and returns the result.
The addNums function can now be used/called within the code:
Example 20.09
Create a program that has a function to take two values as parameters and multiply them.
The main program should then call the function, first with the number 2 and 3, secondly
with the numbers 4 and 5, thirdly with the result of the first function call and the second
function call. Then display the result from the third function call.
Self-invoking/self-calling functions
Runs automatically when a page loads i.e. it calls itself.
26
To do that we put the function within brackets and include its actual parameter value(s)
after its definition, again in brackets.
Example
<html>
<script>
(function say_hello(text) {
alert(text);
}) (“I am calling myself!”);
</script>
</html>
Example
Below statement generates a random number between 1 and 10 and store it in the
variable RandomNumber.
var RandomNumber=Math.floor(Math.random()*10) + 1;
Local variable
A variable declared within a function and can only be accessed (assigned, accessed,
changed) within that function.
It only exists when that function is running. As soon as the function finishes and returns
control, the local variables disappear/cease to exist.
Global variable
A variable declared outside the functions and thus can be accessed anywhere within the
whole program.
It exists as soon as the webpage loads and continue to exist throughout the execution of the
whole program. This can, however, wastes memory because it will always exist.
Example
27
NB number is global while newNumber is local.
28
29
FORM ELEMENTS
All code to display controls such as buttons, drop-down boxes, option buttons, text boxes
etc. can come within the <form></form> tags.
<form> tags tell HTML that we are creating a form.
Object – a data type where a series of named values are stored under one identifier. It can
be used to create a record.
An event can occur within HTML code that can be acted upon by JavaScript e.g. when a
button is clicked.
A JavaScript function can be called to perform an action for an event.
30
Text box
Button
A clicked button can be programmed to call a JavaScript function.
Example
Below HTML code will create a button called “Click me”:
function outputMessage() {
document.write(“Hello World!”);
}
Example 20.10
Create a program that displays an image when a button is clicked.
31
32
Text box
Data can be input from the user through a text box and then used e.g. in a calculation.
33
Create a text box in HTML code and give it an identifier using the <input> tag with its type
property set to the value text, number etc.
NB <input> tag, <br> tag etc are empty tags. This means that they don’t have content and
closing tags.
document.getElementById(“enterColour”).value=”Hello”;
NB Data input through a text box is stored as a string, number etc. depending on the value
set for the type property.
E.g if its set to text then the value is stored as a string unless it is converted to another data
type e.g. number value using say the Number() function.
E.g. if the type property was set to text and the number 22 was input, this would be stored
as the string value “22”.
Example
In below example, the value entered through the text box will be a number data value and
the text box is initialised to a blank/null value.
NB Data input through the text box can also be accessed using the .value property of the
text box as below.
Also note that the type property of the text box was not set so that the value input will be
of any data type.
Example 20.11
34
Create a program that asks the user to enter two numbers, one in each separate text box.
When the button is clicked, add these numbers together and output the result to the
same two text boxes.
35
Drop-down box
It gives the user a list of options from which to choose one at a time during data input.
The drop-down box is created using the HTML <select> tag.
The list options are then specified using the <option> tags nested within the <select> tags
as below.
document.getElementById (“colours”).options*document.getElementById
(“colours”).selectedIndex+.text;
36
Notice that document.getElementById (“colours”) appears twice in the same line. Thus,
instead of writing it twice, you can store this in a variable e.g.:
coloursID.options[coloursID.selectedIndex].text;
Example
The above code has been put in a function invoked by a button.
The function will access the chosen option and output it in an alert.
Radio/option buttons
It gives the user a range of options from which to choose one at a time during data input.
It uses the HTML <input> tags with the type property set to the value radio, name property
set to the special option buttons array (that stores option button values) and value property
set to an individual option.
Example
Below HTML code will create a radio button for the colour options Purple, Orange and Blue:
37
NB The radio buttons must be within a form/<form> tags so that they are grouped together
otherwise the user may be able to select several options at a time.
Check which option has been selected by the user using a function with a looping structure.
The loop checks each of the radio buttons, in turn, to find out which one has been
checked/selected e.g.:
38
document.forms[] is a special webpage array that stores all form controls inserted on the
webpage where the first form control is stored at the 0th array location.
The first line in the function stores the HTML document’s first/0th form elements in the
array variable “colour” i.e. in this case the three radio button options.
The for loop goes through each “colour” array element; 0, then 1, then 2.
Each time it checks if that radio button has been selected by the user.
The next line only runs if the “if” is true, then it outputs the content of the choice (the
colour chosen).
NB The <br> tag inserts a line break in a webpage and thus ensures that each option button
is on its own line.
Q: Compare and contrast the use of a drop-down box and option buttons.
39
Example 20.12
Create a program where a user can choose a colour from a drop-down box, and an animal
from a radio button. The program should then combine these and output the name of the
new coloured animal when a button is clicked.
NB Above code has a missing statement just before the for loop:
var animalRadio=document.forms[0];
40
DETECTING EVENTS
Six common events that can be detected and programmed in JavaScript include:
onclick
onload
41
onchange
onmouseover
onmouseout
onkeydown
The above events are regarded as attributes in the HTML elements they are attached to.
onclick
This was already used on section on buttons.
onload
Runs when the HTML element to which it is attached to is called or loaded.
Example
onchange
Attached to an HTML element that the user can change e.g. a drop-down box.
Example
When the user changes their option in the drop-down box, the function will be called.
42
onmouseover
Runs when user moves mouse pointer/cursor over an HTML element.
Example
Below when user points their mouse pointer/cursor over the image, the image will change.
43
onmouseout
It runs when the user moves the cursor/mouse pointer off an HTML element e.g. an image.
Example
When user moves cursor/mouse pointer away from the image, a different function is called
which displays a different image.
44
onkeydown
The function runs when the user presses a key or types a character on the keyboard when
the function is attached to an HTML element where user can enter data e.g. a text box.
45
NB Small functions and their definitions or just their bodies can be directly specified in the
event attribute e.g.:
document.getElementById(“text1”).style.visible=”hidden”;
46
Example 2-Using the display property
Below code makes the above text box invisible:
document.getElementById(“text1”).style.display=”none”;
.visible vs .display
.visible keeps the space that the hidden item(s) occupied and hence all other existing
elements remain fixed/unchanged on the screen whereas .display completely removes the
space previously occupied by the hidden elements and hence reorganises the existing HTML
elements to occupy that created space.
Example 20.13
Write a program to make an image disappear when the cursor moves over it, and make it
reappear when the mouse/cursor moves off it.
47
SELECTION
It is a conditional statement which lets the programmer specify which statement, if any, will
be executed.
The statement(s) selected for execution depends on some tested condition.
Condition
A statement that can be evaluated to true or false.
e.g.: 5> 6 gives result false because 5 is not greater than 6.
Comparison operators
48
49
Common JavaScript selection statements
if
if..else
if.. elseif..else
switch
ternary operator
NB Be very careful when using conditions as JavaScript is very logical and it is important to
give instructions very precisely as JavaScript doesn’t have any common sense.
if
Checks a condition and if true, runs the first block of code.
It is always the first in a selection statement.
Example
if(myVariable < 6){
message=”Yes it is!”;
}
else
It gives the option to run some code if the condition within the if is false:
Example
if(myVariable < 6){
message=”Yes it is!”;
}else{
message=”No it isn’t!”;
}
else if
Allows multiple conditions to be set to different outcomes.
There can be as many else if conditions as needed.
If the else clause is included, then it must be at the very end.
50
Example 20.14
Create a program that displays a different image depending on which option was chosen
from a drop-down box.
51
Logical operators
Allows a comparison to include more than one statement.
The three common logical operations are: AND, OR and NOT.
Logical operators are also used in loops.
Example 20.15
52
Create a program that asks the user to enter two numbers and output a message
depending on the numbers.
If either number is less than 10, output “Too small”.
If either number is greater than 100, output “Too large”.
If both numbers are less than 50 and greater than 10, output “Below”.
If both numbers are greater or equal to 50 and less than 100, output “Above”.
Otherwise, output “Mixed”.
NB The later else ifs did not need to check that the number was above 10, or less than 100.
This is because the if statements run in order, so if the condition is true, then none of the
other preceding comparisons will take place and hence the program will jump to the last }.
53
NB Combining multiple ifs can get difficult to manage and less efficient. In such cases, a
switch statement is more efficient because it does not perform all the conditions every
time.
switch
Takes a variable/expression and then checks its value against a series of options that can be
values or variables.
Example
54
55
The value stored in variable number is compared to the first case statement i.e. case 4. If it
is equal to it, it will write It’s 4 into the variable message. Then run the break statement
which forces it to break out of the switch statement i.e. it will not then compare the value
with the next case.
The default statement catches a value that is not caught by any of the previous case
statements.
Example
Below code gets today’s date from the system and then determines whether it’s a
Saturday, Sunday or not in which case it outputs that we are looking forward to weekend.
<html>
<h2>Javascript switch</h2>
<p id=”demo”></p>
<script>
var text;
var day= new Date().getDay();
switch(day){
case 0:
text=”Today is Sunday ”;
break;
case 6:
text=”Today is Saturday ”;
break;
default:
text=”Looking forward to weekend”;
}
document.getElementById(“demo”).innerHTML=text;
</script>
</html>
Ternary operator
It is a special type of selection statement with a single comparison.
It assigns a value to a variable and the value assigned depends on whether this comparison
is true or false.
Example
var valueToUpdate=(inputData < 10)? “Below”: “Above”;
If the value in variable inputData is less than 10, then store “Below” in the variable
valueToUpdate, otherwise store “Above” in variable valueToUpdate.
56
57
ARRAYS
Array
A data structure that can store multiple data items of the same data type under one
identifier/name.
The data values can be integers, real numbers, strings, Boolean, objects, images etc.
It is often presented as a list/table where each stored value is given a number with which to
access it called the array index or subscript.
In JavaScript and most other languages, array indices start at 0 rather than 1.
An array is stored in contiguous/consecutive memory locations.
58
The two main types of arrays are 1D arrays and 2D arrays.
Example 1: A 1D array
var colours=*“orange”, “purple”, “green”, “yellow”, “grey”+;
The code above declares an array called “colours” with five elements/data values stored in
computer memory as below:
Index 0 1 2 3 4
Value orange purple green yellow grey
Example 20.16
Store five words in an array. Create a webpage that asks the user to enter a number
between 1 and 5 and display the word in that index.
59
60
LOOPS
It is a construct that repeats the code inside it a set number of times based on a condition.
It is also called looping or iteration or repetition.
Used to perform the same action multiple times.
It reduces the amount of code in a program which makes it run faster and occupy less
storage space.
Types of loops
Count-controlled loops
Condition-controlled loops
61
Count-controlled loop
Repeats a set/fixed number of times e.g. for loop.
Used when you know in advance how many times the code needs to repeat.
Condition-controlled loop
Repeats as long as a condition is true e.g. while and do/while.
Used when you do not know in advance how many times the code needs to repeat.
for
Programmer must know the number of times the loop must run.
Example
The following code adds the value of the total variable to itself ten times.
total=1;
for (count=0; count<10; count++) {
total=total + total; //loop body
}
Loop control variable count above counts number of times a loop is run. This statement
can be excluded, if for example, you want to use a variable that already exists.
Loop condition – count<10 above. As long as this condition is true, the loop will run.
This statement can be excluded but this will cause the loop to run
continuously/infinitely unless you include a break statement within the loop body.
62
Break statement- line of code that tells the program to stop the construct it is currently
in e.g. the loop above and go to the next line of code after the loop.
Loop control variable increment-count++-increments the loop control variable. This
statement can be excluded if, for example, you want to change the variable elsewhere
within the loop.
Loop body- total=total + total;- it is zero or more statements repeated as long as the
loop condition is true.
Example 2
for(count=1; count<=12; count++){
alert(count*count);
}
for/in
Used to loop through an object one element at a time e.g. to output them all such as from
an array, a record structure etc.
Example
Below code outputs each of the elements within the object film.
63
while
Runs the code while a condition is true.
Example
64
Above loop displays the first 12 square numbers.
A loop counter/control variable is declared before the loop body and its value is checked in
the loop condition.
The loop counter is incremented within the loop.
The above loop will run infinitely i.e. while the variable check is true, it will continue to run.
Infinite loops are in most cases a programming error.
The loop control variable will need to change within the loop so that at some stage, it is no
longer true.
A break statement can also be inserted into a loop to stop it running e.g. a selection (if)
statement within a loop could catch a condition that calls break;.
do/while
Condition is checked at the end of the loop meaning loop will always run at least once.
Example
65
while vs do while loops
while may never run the code inside it whereas do while will always run the code at
least once.
while checks condition at start of loop whereas do while checks condition at end of
loop.
while runs the code as long as the condition is true whereas do while runs the code as
long as the condition is false.
Example 20.17
Create a program that asks the user to enter their username and password. All valid user
names and passwords are stored in a 2D array (username in one index, password in the
other). Output whether the user has got it correct or not.
66
NB Above the input box is set to type “password”. This means “*”s will appear instead of
the password when text is typed into the box for security purposes by avoiding shoulder
surfing.
Q: The above code has omitted two statements that pertains to the flag variable. Identify
them and add them.
A: 1. Declare the flag variable outside the for loop and initialise it to false:
var flag=false;
2. Reset the flag variable to true within the true/then part of the if statement:
var flag=true;
67
TIMING EVENTS
Usually, JavaScript code runs without any delay i.e. as long as the page loads.
However, if necessary, we can include a delay using the two built-in functions- setTimeout
and setInterval.
JavaScript has an in-built timer that allows you to delay running a function or performing an
action at a set interval.
The setTimeout and setInterval in-built functions can be used/called within a user-defined
function.
setTimeout
Used to set a delay before something happens e.g. before a function is called, before an
output appears on screen etc.
Call structure/syntax:
68
setTimeout(function(){
Event to delay;
}, timeToDelay);
Where:
setTimeout -is the delay built-in function with two arguments/parameters- a user-
defined named or nameless function name (header)/definition that performs a
function/action to be delayed and the delay time in milliseconds.
timeToDelay – time to delay in milliseconds.
NB Time to delay is in milliseconds where 1 second=1000 milliseconds. Hence, 3
seconds=3000, 4 seconds=4000 etc.
Example
In this example, we wait for 5000 milliseconds (5 seconds) and then write out “Happy Birth
Day”.
<html>
<p id=”demo”></p>
<script>
setTimeout(myGreeting,5000);
function myGreeting(){
document.getElementById(“demo”).innerHTML=”Happy Birth Day”;
}
</script>
</html>
Example 20.18
69
Create a webpage that makes a line of text appear, then an image, then another line of
text, then another image, with a two-second delay between each.
setInterval
Allows you to make something happen repeatedly at a set/fixed time interval
e.g. output the same alert box every two seconds, execute some function every four
seconds etc.
The repeated function or operation will go on forever until stopped in some way e.g. using
the clearInterval built-in function or location.reload() built-in function.
Call structure/syntax:
setInterval(function(){
Event to repeat;
}, timeBetweenRepeats);
In above code, the alert appears every 1 second and will repeat forever.
70
The nameless function inside both setTimeout and setInterval can include more than one
line of code.
Example
var counter=0;
function delayOutput(){
setInterval(function(){
alert(counter);
counter++;
},1000);
Above code declares and initialises a global variable counter and then outputs its value and
increments it, every second.
Only one delay can run at a time because JavaScript cannot support multiple threads
running.
Thus, each interval will be one thread that is running.
We can stop the interval/repetition by using the function clearInterval(). To know which
interval to stop, we need to store the interval in a variable first.
E.g:
var myInterval=setInterval(some_function(), time);
clearInterval(myInterval);
Example 1
<html>
<p id=”demo”></p>
<script>
setInterval(displayHello, 1000);
function displayHello(){
document.getElementById(“demo”).innerHTML=”Hello”;
}
</script>
</html>
Example 1
71
Below example includes a button which stops adding the text “Hello” to the given
paragraph.
<html>
<p id=”demo”></p>
<button onclick=”stop_saying_hello()” >Stop</button>
<script>
var myInterval= setInterval(displayHello, 1000);
setInterval(displayHello, 1000);
function displayHello(){
document.getElementById(“demo”).innerHTML=”Hello”;
};
function stop_saying_hello() {
clearInterval(myInterval);
}
</script>
</html>
Example 2
Below code stops the above function being indefinitely called (using the setInterval
function) by using the location.reload() function.
Example 20.19
Create a webpage that outputs the next element on an array of colours every two
seconds.
72
NB The if statement was included to avoid an array/subscript out of bounds run-time error
because count keeps incrementing and if it gets to 6, there is no sixth element in the array.
73
STRING MANIPULATION
Allows actions to be performed on a string/text value e.g. extract a substring from it.
The first letter in a string is letter 0, the second is letter 1 etc.
Spaces and all symbols all count as characters.
74
Example 20.20
Create a webpage that generates a username for a user. The username uses the last three
characters of their last name, the first four characters of their first name, and the year
from their date of birth. Output their username to the user.
75
76
77
COMMENTS
It is text added to code which the language translator program/JavaScript interpreter
ignores.
Used to make notes about/explain how your code works so other software
developers/programmers can understand the code so that they can change it or improve it.
Used to explain amendments or additions made to code.
Used to explain purpose of a program/module, date it was written, name of programmer
who created/amended it.
78
ITERATIVE METHODS/FUNCTIONS
These are functions/tasks that are repeated usually to each element of a data structure such
as an array.
They are special built-in functions in JavaScript which take in a user-defined function as a
parameter.
Based on the Object-Oriented Programming (OOP) concept.
Syntax
<variable> = <data structure>.<method>
E.g:- <variable>=<array>.<method>
every method
Checks every element in an array against a condition.
It returns true if all items meet the condition or false if at least one element does not meet
it.
Example
function isTen(item) {
return (item==10);
};
79
An array numbers is declared. The user-defined function isTen is applied to the array using
the every method:
var everyCheck=numbers.every(isTen);
Above code:
Declares an array called numbers and populates it with values.
Calls an every method and sends the array elements to it one at a time using the code
function (item, index, array).
the condition is item==10
the result of this is returned and stored in the variable everyCheck.
The above code will return false because not all elements in array numbers are equal to 10.
some method
It is a Boolean function which checks if at least one item meets the condition.
If at least one of the elements meets the condition, it returns true.
Example
function equalTen(item){
return(item==10);
};
The some method/function will return true because at least one of the elements is equal to
10.
filter method
Returns a sub-array/sub-list with all the elements that meet the criteria.
Example
function lessThirtyFive(item, index, array){
return (item<=35);
};
80
The method will return [10, 20, 30] because these are all the elements that are less than or
equal to 35.
forEach method
It runs a task/operation/command on every element within an array, but the effects of the
operation/editing are not saved.
It does not return any value.
Example
function addOne(item, index, array){
item=item+ 1;
document.write(item);
};
The method will take each item in the array, add 1 to it, then output the new value.
However, the actual values stored in the array are not changed.
map method
Runs a task/command/operation on every element within the array and returns the new
edited array/saves the changes.
Example
function mapOne(item, index, array){
item=item+ 1;
};
The method will return the following edited values that are now stored in the new array
mapArray: 11, 21, 31, 41, 51, 61.
Example 20.21
Create a webpage that checks if every number stored in an array is greater than zero.
81
82
TRAP ERRORS
Errors can occur in a variety of places in a program and for a variety of reasons e.g.:
Invalid data input by the user.
Attempt to perform an impossible calculation such as multiplying two text values,
division by zero, trying to find square root of a negative value etc.
Errors made by programmers themselves.
83
try and catch code blocks are used to trap errors e.g. to validate data on entry.
The try block contains statements that are attempting to run. A specific error message can
be thrown to be output after each statement. It uses the throw keyword.
The catch block states what to do with the error message if generated.
Example
var x=21;
try{
if(x>20) throw “over 20”;
if(x<=10) throw “less than 11”;
}
catch(e){
message.innerHTML=e;
}
The catch block takes this error message, if it is generated, and then displays it.
Using separate if statements (without the else clause) above will ensure that all possible
error conditions are tested whereas a case statement, if..else, if.. else if.. statements may
not catch all possible errors.
84
USING EXTERNAL SCRIPTS
JavaScript code can be written in a separate document/file and then imported into an HTML
document.
Create a separate document and write your JavaScript code inside it.
Save the file with a sensible name and extension .js
Files that specifically store JavaScript code end in .js.
Inside this document, write the JavaScript code that would usually go within the JavaScript
(<script>…</script>) tags.
It helps keep things more organised.
Example
Type below JavaScript code in your editor e.g. Dreamweaver and save it in a file with
extension .js
var value1=5;
var value2=10;
document.write(value1*value2);
85
Next, call this code within your HTML document where the name of the JavaScript file goes
within the <script> tags using the src attribute.
In this example, the JavaScript file “javascriptparagraph.js” is being imported into this
webpage.
<html>
<script src=”javascriptparagraph.js”></script>
</html>
The <script> tags make sure that the JavaScript is included/incorporated in the HTML file.
The src attribute specifies the JavaScript file name and location.
In above example, make sure that the html file and the JavaScript file are in the same folder.
86
87