Programming in Design  
Lecture 05 Introduction to JavaScript  
Edirlei Soares de Lima  
<edirlei.lima@universidadeeuropeia.pt>  
What is JavaScript?  
JavaScript is a scripting language that is used to add interactivity  
and behaviors to web pages.  
JavaScript can update and change both HTML and CSS, calculate,  
manipulate and validate data.  
JavaScript is a full programming language that contains variables,  
functions, conditional statements, loop statements, data structures, etc.  
<script>  
function myFunction(a, b)  
{
var result = a * b;  
return result;  
}
var x = myFunction(2, 5);  
document.getElementById("resultlocation").innerHTML = x;  
</script>  
What JavaScript Can Do?  
Dynamically detect that a username is not available and then  
inserts a message and alters styles to make the problem  
apparent.  
What JavaScript Can Do?  
Automatically complete a search term as it is typed in.  
Show and hide content based on a user clicking on a link or  
heading, to create a “collapsible” content area  
What JavaScript Can Do?  
Load an image or content in a custom styled “lightbox”  
(
thumbnail version of the image.  
isolated on the page using CSS) after a user clicks on a  
What JavaScript Can Do?  
JavaScript can change HTML content, attribute values, and  
CSS properties;  
JavaScript can load content into the document if and when  
the user needs it, without reloading the entire page (this is  
commonly referred to as Ajax).  
JavaScript can test for what is possible in your browser and  
react accordingly.  
Etc…  
Adding JavaScript to a Page  
Like CSS, you can embed a script right in a document or keep  
it in an external file and link it to the page.  
Both methods use the script element.  
Embedded script:  
<script>  
</script>  
External scripts:  
<script src="my_script.js"></script>  
Simple Example  
Embedded script:  
<
<
!DOCTYPE html>  
html lang="en">  
mypage.html  
<head>  
<
<
title>Page Title</title>  
script>  
function myFunction() {  
document.getElementById("mytext").innerHTML = "Text changed by  
JavaScript!";  
}
</script>  
<
<
/head>  
body>  
<
<
p id="mytext">This is a text.</p>  
button type="button" onclick="myFunction()">Click here!</button>  
</body>  
</html>  
Simple Example  
External script:  
myscript.js  
function myFunction() {  
document.getElementById("mytext").innerHTML = "Text changed by  
JavaScript!";  
}
<
!DOCTYPE html>  
mypage.html  
<html lang="en">  
<head>  
<title>Page Title</title>  
<script src="myscript.js"></script>  
<
<
/head>  
body>  
<
<
p id="mytext">This is a text.</p>  
button type="button" onclick="myFunction()">Click here!</button>  
</body>  
</html>  
Variables and Constants  
Variables and constants are the basic elements manipulated  
by a script.  
Constant is a fixed value that doesn’t change during the  
execution of a script.  
ꢅꢆꢃꢇꢈ1 + ꢅꢆꢃꢇꢈ2  
ꢁꢂꢃꢄꢅꢆꢃꢇꢈ =  
2
Contant value  
Variables  
Variable is a space in the memory of the computer that is  
reserved to store a specific type of data.  
Containers where we can store information (numbers, text, etc.)  
Variables have names so they can be referenced in the code and  
have their values accessed or changed when necessary.  
Variable Grade1  
Variable Grade2  
ꢅꢆꢃꢇꢈ1 + ꢅꢆꢃꢇꢈ2  
ꢁꢂꢃꢄꢅꢆꢃꢇꢈ =  
2
Variable FinalGrade  
Variables  
The content of a variable can change during the execution of a  
script.  
Although different values can be assigned to the same variable,  
it can only store one value at a time.  
“7.5”  
“8.0”  
ꢅꢆꢃꢇꢈ1 + ꢅꢆꢃꢇꢈ2  
ꢁꢂꢃꢄꢅꢆꢃꢇꢈ =  
2
“7.75”  
Variables  
Variables have:  
Name: used to refer to the variable in the code;  
Name restrictions: is not allowed to start the name of variable with a number (0-9),  
some special characters are not allowed in the names (*, -, /, +, ...), and some  
reserved word can not be used as well (if, for, while, ...).  
Type: defines the set of values that can be stored in the variable;  
Value: the value stored;  
Variables must be:  
Declared: What is the name and what is the type of the variable?  
Initialized: What is the initial value of the variable?  
Variables in JavaScript  
JavaScript is a dynamically typed language. This means that  
when a variable is declared, its type doesn’t need to be  
specified.  
There are no type definitions in JavaScript;  
Each value carries its own type.  
Type  
Examples of Values  
number  
string  
0, 1, 2.3, -2.3  
hi”, “hello world”,test 123”, “”  
true, false  
boolean  
function  
table  
0x1234567  
0x2345678  
thread  
0x3456789  
userdata  
undefined  
0x4567890  
undefined  
Declaring Variables  
Variables must be explicitly declared;  
More than one variable can be declared at a time;  
Examples:  
var a;  
// declares a variable called a  
var b;  
// declares a variable called b  
var d, e;  
var d = 5;  
// declares two variables (d and e)  
// declares and initializes the variable d  
var f = "test"; // declares and initializes the variable f  
var g = 1, h = 6;// declares and initializes the variables g, h  
Arithmetic Operators  
Arithmetic Operators are used to perform arithmetic  
operations with variables and constants.  
Operation  
Symbol  
Examples:  
assignment operator  
Addition  
+
-
Subtraction  
Multiplication  
Division  
total = price * quantity;  
final_grade = (grade1 + grade2)/2;  
result = 3 * (1 - 2) + 4 * 2;  
*
/
Remainder or modulus  
Exponentiation  
Increment  
%
**  
++  
--  
res = 4 % 2;  
res = b ** 2;  
x++;  
y--;  
Decrement  
Example 1  
Problem: read two numbers and show the sum of the numbers.  
<body>  
<p id="mytext">Enter the two number to add:</p>  
Number 1: <input type="text" id="firstnumber"><br>  
Number 1: <input type="text" id="secondnumber"><br><br>  
<
<
button type="button" onclick="AddNumbers()">Calculate</button>  
br><br><p id="result"></p>  
</body>  
function AddNumbers()  
{
var number1, number2, result;  
number1 = parseInt(document.getElementById("firstnumber").value);  
number2 = parseInt(document.getElementById("secondnumber").value);  
result = number1 + number2;  
document.getElementById("result").innerHTML = "Result: " + result;  
}
Functions  
A function is a block of code with a name that can be executed  
at other points in the code.  
It may have parameters  
It may return a result  
Functions are important to:  
Simplify and organize the code (modularization);  
Avoid repetitions of code;  
Extend the programming language;  
Once declared, we can just use them (abstraction)  
Functions in JavaScript  
A script cannot have two  
functions with the same name.  
function function_name(parameter1, parameter2)  
{
var variables  
JavaScript instructions  
If a function doesn’t have  
return  
parameters, we just use: ()  
}
Block of code  
Example 2  
Problem: convert from celsius to fahrenheit.  
function celsius_fahrenheit(tc){  
var f;  
f = 1.8 * tc + 32;  
return f;  
}
<head>  
<
<
title>Page Title</title>  
script src="myscript.js"></script>  
<
<
/head>  
body>  
<p>Celsius to fahrenheit: <b id = "result"></b></p>  
<script>  
document.getElementById("result").innerHTML =  
celsius_fahrenheit(23);  
</script>  
</body>  
Example 3  
Problem: calculate the volume of a cylinder.  
function volume_cylinder(r, h){  
var volume;  
volume = Math.PI * (r ** 2) * h;  
return volume;  
}
<head>  
<
<
title>Page Title</title>  
script src="myscript.js"></script>  
<
<
/head>  
body>  
<p>Volume of the cylinder: <b id = "result"></b></p>  
<script>  
document.getElementById("result").innerHTML =  
volume_cylinder(2, 4);  
</script>  
</body>  
Exercise 1  
1) Write and test functions that:  
a) Convert kilometers per hour to miles per hour (1 km/h is  
equal to 0.6213711922 mi/h).  
b) Calculate the perimeter of a rectangle (= 2 * ( ꢁꢂꢃꢄ +  
ꢆꢇꢈꢅ)).  
c) Take hours and minutes as input, and calculate the total  
number of minutes.  
d) Take minutes as input, and display the total number of  
hours and minutes.  
JavaScript Events  
HTML events are "things" that happen to HTML elements.  
When JavaScript is used in HTML pages, JavaScript can "react" on  
these events.  
It can be something the browser does, or something a user does.  
Examples:  
An HTML web page has finished loading;  
An HTML input field was changed;  
An HTML button was clicked;  
JavaScript lets you execute code when events are detected.  
Example (onclick event):  
<button type="button" onclick="myFunction()">Click here!</button>  
JavaScript Events  
Common HTML Events:  
onchange: an HTML element has been changed;  
onclick: the user clicks an HTML element;  
onmouseover: the user moves the mouse over an HTML element;  
onmouseout: the user moves the mouse away from an HTML element;  
onkeydown: the user presses a keyboard key;  
onload: the browser has finished loading the page;  
Complete list of events:  
https://www.w3schools.com/jsref/dom_obj_event.asp  
JavaScript Events  
Example: mouse events  
<div onmousemove="myMoveFunction()">  
<p>onmousemove: <br> <span id="block1"></span></p>  
</div>  
<div onmouseenter="myEnterFunction()">  
<p>onmouseenter: <br> <span id="block2"></span></p>  
</div>  
<div onmouseout="myOutFunction()">  
<p>onmouseout: <br> <span id="block3"></span></p>  
</div>  
div {  
width: 120px;  
height: 100px;  
border: 1px solid black;  
margin: 10px;  
float: left;  
padding: 30px;  
text-align: center;  
background-color: lightgray;  
}
JavaScript Events  
Common mouse events:  
var x = 0;  
var y = 0;  
var z = 0;  
function myMoveFunction(){  
x = x + 1;  
document.getElementById("block1").innerHTML = x;  
}
function myEnterFunction(){  
y = y + 1;  
document.getElementById("block2").innerHTML = y;  
}
function myOutFunction(){  
z = z + 1;  
document.getElementById("block3").innerHTML = z;  
}
JavaScript and HTML DOM  
When a web page is loaded, the browser creates a Document  
Object Model of the page.  
By accessing the DOM model, JavaScript can change all the HTML  
elements, attributes and CSS styles in the page, remove existing HTML  
elements, add new HTML elements, etc.  
JavaScript and HTML DOM  
Finding HTML Elements:  
document.getElementById(id) - find an element by element id;  
document.getElementsByTagName(name) - find elements by tag name;  
document.getElementsByClassName(name) - find elements by class  
name;  
Changing HTML Elements:  
element.innerHTML = new html content - change the inner HTML of an  
element;  
element.attribute = new value - change the attribute value of an HTML  
element;  
element.style.property = new style - change the style of an HTML  
element;  
Example 1 getElementById  
Finding HTML Element by id:  
<p id="mytext">This is a text.</p>  
<button type="button" onclick="FindByID('mytext')">Click here!</button>  
function FindByID(myid)  
{
document.getElementById(myid).innerHTML = "Hello World!";  
}
Example 2 getElementsByTagName  
Finding HTML Elements by tag name:  
<
<
<
<
p>This is a text.</p>  
p>This is a text.</p>  
p>This is a text.</p>  
button type="button" onclick="FindByTag('p')">Click here!</button>  
function FindByTag(tag)  
{
var allp = document.getElementsByTagName(tag);  
allp[0].innerHTML = "Hello World!";  
allp[1].innerHTML = "Hello World!";  
allp[2].innerHTML = "Hello World!";  
}
Example 3 getElementsByTagName  
Finding HTML Elements by tag name (using a for loop):  
<
<
<
<
p>This is a text.</p>  
p>This is a text.</p>  
p>This is a text.</p>  
button type="button" onclick="FindByTag('p')">Click here!</button>  
function FindByTag(tag)  
{
var allp = document.getElementsByTagName(tag);  
for (var i = 0; i < allp.length; i++)  
{
allp[i].innerHTML = "Hello World!";  
}
}
Example 4 getElementsByClassName  
Finding HTML Elements by class name (using a for loop):  
<
<
<
<
<
<
<
p>This is a text.</p>  
p class="changeable">This is a text.</p>  
p class="changeable">This is a text.</p>  
p>This is a text.</p>  
p class="changeable">This is a text.</p>  
p>This is a text.</p>  
button type="button" onclick="FindByClass('changeable')">OK</button>  
function FindByClass(classname)  
{
var allp = document.getElementsByClassName(classname);  
for (var i = 0; i < allp.length; i++)  
{
allp[i].innerHTML = "Hello World!";  
}
}
Example 5 getElementsByTagName  
Finding HTML Elements by tag name (using a for loop and a if):  
<
<
<
<
<
<
<
p>This is a text.</p>  
p class="changeable">This is a text.</p>  
p class="changeable">This is a text.</p>  
p>This is a text.</p>  
p class="changeable">This is a text.</p>  
p>This is a text.</p>  
button type="button" onclick="FindByTagClass('p', 'changeable')">  
OK</button>  
function FindByTagClass(tag, changeclass){  
var allp = document.getElementsByTagName(tag);  
for (var i = 0; i < allp.length; i++)  
{
if (allp[i].className == changeclass)  
{
allp[i].innerHTML = "Hello World!";  
}
}
}
Example 6 Changing Attributes  
Changing the value of an attribute:  
<
<
<
img id="lightimage" src="images/light_off.gif"><br>  
button type="button" onclick="TurnOn('lightimage')">On</button><br>  
button type="button" onclick="TurnOff('lightimage')">Off</button><br>  
function TurnOn(lightid)  
{
document.getElementById(lightid).src = "images/light_on.gif"  
}
function TurnOff(lightid)  
{
document.getElementById(lightid).src = "images/light_off.gif"  
}
Example 7 Animation  
JavaScript animations are done by programming gradual  
changes in an element’s attributes and style:  
div.container {  
width: 400px;  
height: 400px;  
position: relative;  
background: green;  
}
div.animatedobject {  
width: 50px;  
height: 50px;  
position: absolute;  
background-color: red;  
}
<
<
p><button onclick="AnimateSquare()">Animate</button></p>  
div class="container">  
<div class="animatedobject" id="mysquare"></div>  
</div>  
Example 7 Animation  
JavaScript animations are done by programming gradual  
changes in an element’s attributes and style:  
function AnimateSquare(){  
var square = document.getElementById("mysquare");  
var position = 0;  
var id = setInterval(frame, 2);  
function frame(){  
if (position < 350){  
position++;  
square.style.top = position + "px";  
square.style.left = position + "px";  
}
else{  
clearInterval(id);  
}
}
}
Assignment 3: Interactivity  
Design and implement interactive and dynamic elements for  
the storytelling website.  
Use the basic layout created in the second assignment as the starting  
point;  
The final website must include the story content (e.g. text, images,  
animations, hyperlinks) and allow users to navigate and interact with  
the story;  
Deliverables: source code and all resources used in the website.  
Further Reading  
Robbins, J. N. (2018). Learning web design: A beginner’s guide to HTML,  
CSS, JavaScript, and web graphics (5th ed.), O'Reilly Media. ISBN: 978-  
1491960202.  
Chapter 19: Introduction to JavaScript  
Chapter 20: Using JavaScript