Professional Documents
Culture Documents
on
Introduction to Programming using JavaScript
BACHELOR OF TECHNOLOGY
In
ELECTRONICS AND COMMUNICATION ENGINEERING
By
MALINENI DEEKSHA
(15K41A0494)
SR ENGINEERING COLLEGE
CERTIFICATE
I wish to take this opportunity to express my sincere gratitude and deep sense of respect to
our beloved Principal, Dr. V. MAHESH, for his continuous support and guidance to complete
this certification course in the institute.
I express my heartfelt thanks to our Head of the department Dr. J.TARUN KUMAR, for
providing me with necessary infrastructure and thereby giving me freedom to carry out the
certification course.
I express my heartfelt thanks to coordinator P.ANJALI, for her encouragement and support.
Finally, I would like to thank all the teaching and non-teaching staff of the department for
their suggestions and timely support.
iii
OBJECTIVE
iv
CONTENTS
Acknowledgement iii
Objective iv
List of Acronyms vi
1 INTRODUCTION
1.1 About JavaScript 1
1.2 Object oriented programming 2
2 CERTIFICATION COURSE(MTA)
2.1 What Makes JavaScript Unique? 5
2.2 How to Run JavaScript? 5
2.3 Tools You Need 5
2.4 How Is JavaScript Constructed? 5
2.5 Adding A Script to The Page 6
BIBLIOGRAPHY 38
v
LIST OF ACRONYMS
ACRONYMS ABBREVATIONS
MTA Microsoft Technology Associate
UI User Interface
vi
CHAPTER 1
INTRODUCTION
JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a
popular browser of that time. When JavaScript was first released it was called Mocha. As a
marketing ploy to gain the acceptance it was later named as “JavaScript”. There are many
programmers who think that JavaScript and Java are the same. In fact, JavaScript and Java
are very much unrelated. Java is a very complex programming language whereas
JavaScript is only a scripting language. The syntax of JavaScript is mostly influenced by
the programming language C.
2
An array can have numbers in its cells. As we have already discussed, the array is an object,
and so would be a cell within it, and so is the content of the cell. We cannot refer to the cell
itself, but we can refer to its contents: myArray['cell name or number'] .
-Classes (or types)
A class is a group of objects that are similar in some way. For example, a number and
a piece of text can both be stored as a variable (in a way, like the variables you would use in
mathematical algebra). We can say that pieces of text and numbers are examples of class
'variable'. Numbers can be sub divided into two groups, integers and floats (or doubles).
Integers are whole numbers: 1, 2, 3, 4, 0, -1, -2, etc. Floats have decimal points: 1.1, -5.7, 0.5,
etc. In this case, we can say that 3 is an instance of class variable, (sub)class number,
(sub)class integer.
In fact, a variable is a type of object. All instances of class 'object' have a certain two
methods: toString() and valueOf().Therefore, as 3 is an instance of class object, (sub)class
variable, (sub)class number, (sub)class integer, it will inherit the toString() and valueOf()methods
The properties of the image would be src, name, height, width, alt and if we also used Style
Sheets we might have included several more (like background-color for example). All
properties are a type of object so to refer to the src of my image, I would write
document.images['myImage'].src
3
-Methods
There are always actions that are associated with objects. For example, a form may be
submitted or reset. The actions are methods. To submit a form in non-object-oriented
programs, we might write submit('name of form').That would simply be a function. In object-
oriented programming like JavaScript, we would use document.nameOfForm.submit().The
reason this is a method and not just a function is that each form will have its own submit()
function built in, which is referred to using the object-oriented syntax shown above. You will
never have to write methods in yourself unless you create your own objects, the browser does
that for you. You can think of it like this:
With the non-object-oriented way, we would tell a function to submit the form.
With the object-oriented way, we would tell the form to submit itself.
If wanted, you can run several methods in turn on the same object by using:
referenceToTheObject.method1().method2().method3().method1again()
In this case, method1 must return a class of object that has the method 'method2' etc.
CHAPTER 2
CERTIFICATION COURSE
4
What Makes JavaScript Unique?
Being a scripting language, JavaScript cannot run on its own. In fact, the browser
is responsible for running JavaScript code. When a user requests an HTML page with
JavaScript in it, the script is sent to the browser and it is up to the browser to execute it. The
main advantage of JavaScript is that all modern web browsers support JavaScript. So, you
do not have to worry about whether your site visitor uses Internet Explorer, Google Chrome,
Firefox or any other browser. JavaScript will be supported. Also, JavaScript runs on any
operating system including Windows, Linux or Mac. Thus, JavaScript overcomes the main
disadvantages of VBScript (Now deprecated) which is limited to just IE and Windows.
The basic part of a script is a variable, literal or object. A variable is a word that
represents a piece of text, a number, a boolean true or false value or an object. A literal is the
actual number or piece of text or boolean value that the variable represents. An object is a
collection of variables held together by a parent variable, or a document component. The next
most important part of a script is an operator. Operators assign literal values to variables or
say what type of tests to perform. The next most important part of a script is a control
structure. Control structures say what scripts should be run if a test is satisfied. Functions
5
collect control structures, actions and assignments together and can be told to run those
pieces of script as and when necessary.
The most obvious parts of a script are the actions it performs. Some of these are done
with operators but most are done using methods. Methods are a special kind of function and
may do things like submitting forms, writing pages or displaying messages.
Events can be used to detect actions, usually created by the user, such as moving or
clicking the mouse, pressing a key or resetting a form. When triggered, events can be used to
run functions. Lastly and not quite so obvious is referencing. This is about working out what
to write to access the contents of objects or even the objects themselves.
To insert JavaScript into a web page, use the <script> tag. You should use the type
attribute to specify the type of script being used, which in the case of JavaScript is
text/JavaScript. It is also possible to the language attribute to say what JavaScript version you
are using. In practice, this number means very little to browsers. They may claim to support a
specific version but will have vastly different capabilities. All JavaScript supporting browsers
currently in use will support a level of JavaScript equivalent to JavaScript 1.2 (represented as
"javascript1.2") or higher, so this is what I will teach you in this tutorial.
Browsers will generally choose an arbitrary version number that they will claim to
support and will run any script that has either no language version number, or a version equal
to or lower than the one they claim to support. Since the language is so unreliable, you should
generally omit this attribute, although it is common to see scripts using it. Your script can
6
then detect if the browser can run your script, and it can do this a lot more accurately than the
version number can. This is an example of a script tag, used to include a script in your page:
<script type="text/javascript">
</script>
If your script is incapable of providing its own fall-back, but it is needed to access the page,
you should include support for non-JavaScript browsers by using:
<noscript>
</noscript>
Using Comments
Comments allow you to leave notes to yourself and other people in your script and are
useful as a reminder of what the script is doing and why. The double slash indicates a single
line comment. Everything after it on the same line will be ignored by the script engine. The
slash-asterisk indicates a block comment. Everything after it will be ignored by the script
engine until an asterisk-slash is encountered.
<script type="text/javascript">
/* This is a
block comment */
7
</script>
You can also use a separate header file to contain the JavaScript (usually *.js) making
it easy to share across pages:
When using header files, if you put any script code in between the <script ...> and
</script> tags, it will only be executed if the browser does not support header files (assuming
it does support the version of JavaScript shown in the language attribute, if you used one).
This is only for very old browsers that are not used at all anymore, so there is no need for
anything to be put there.
Scripts in header files are executed as if they were in the main page. If the script
references any external files, such as images, the addresses it uses are relative to the main
page, not the script URI.
Operators:
JavaScript operators
Operator Uses
adds two numbers or appends two strings - if more than one type of variable is appended,
+
including a string appended to a number or vice-versa, the result will be a string
% divide the first number by the second and return the remainder
the object on the left = the object on the left + the value on the right - this also works when
+=
appending strings
-= the object on the left = the object on the left - the value on the right
number on the left must be greater than the number on the right - this also works with
>
strings and values
8
JavaScript operators
Operator Uses
number on the left must be less than the number on the right - this also works with strings
<
and values
number on the left must be greater than or equal to the number on the right - this also
>=
works with strings and values
number on the left must be less than or equal to the number on the right - this also works
<=
with strings and values
| bitwise OR
^ bitwise XOR
~ bitwise NOT
in object or array on the right must have the property or cell on the left
=== the numbers or objects or values must be equal, and must be the same variable type
!== the numbers or objects or values must not be equal, or must not be the same variable type
Operator Precedence
9
Math object methods
Math.atan2(n, k) Returns the angle (rads) from cartesian coordinates 0,0 to n,k
Math.exp(n) Returns en
Returns ln(n)
Math.log(n)
Note, to find log10(n), use Math.log(n) / Math.log(10)
Math.pow(n,k) Returns nk
Variables
Variable types are not important in JavaScript. They may be interchanged as necessary. This
means that if a variable is a string one minute, it can be an integer the next. The basic variable
types are:
-Character
-String
10
'hdttgs 8 -46hs () Get the idea'
-Integer
0 or 1 or 2 or 3 or 4 etc. or -1 or -2 or -3 or -4 etc.
23.546 or -10.46
-Boolean
true or false
-Function
-Object
-Array
-Regular Expression
-Undefined
-Null
A variable that has been defined but has been assigned the value of null
Integer and float are grouped together as 'number'. Character and string are grouped together
as 'string'.
Use the type of operator to find out which variable type your variable is. Note, typeof
will return 'object' for arrays, regular expressions and null in most current browsers. In future,
browsers are instead expected to return 'null' for null.
11
\n
A newline character. Use this if you want to insert a line break into text.
\f
\r
\t
A tab character.
\\
A \ character
\/
A / character (most web developers [myself included on occasion] forget this one - generally,
browsers will have no trouble with you forgetting the backslash but it is important for
representing closing tags and in theory you should always use the backslash escape when
writing a forward slash - see the section on Writing with script for details of where it is
needed)
Regular Expressions
Some rare browsers do not support regular expressions. In theory, you should be able
to detect regular expression support using this:
12
This should not produce errors in Pocket Internet Explorer and Internet Explorer for
Windows CE (as they do not understand the /pattern/options syntax or support the RegExp
object). However, as Opera 6- and iCab 2- support the RegExp object, but fail to use it
correctly, your scripts will still fail, though hopefully without errors. Thankfully, current
releases of Opera and iCab do support regular expressions correctly.
Writing Functions
Functions group together script code; control structures, operations, method calls, etc.
in the same way as a normal script. These functions can then be called when needed, and the
code contained within them will be run. This makes it very easy to reuse code without having
to repeat it within your script.
function nameOfFunction(listOfVariableNames) {
CHAPTER 3
13
COURSE OUTCOME
Explain separation of concerns and identify the three layers of the web.
Use operators, variables, arrays, control structures, functions and objects in JavaScript.
14
CHAPTER 4
CASE STUDY
RGB GAME
What is the DOM ?
DOM stands for Document Object Model. It’s nothing more than the block level
diagram of all the HTML elements loaded on the page when a browser loads a web page. It is
presented as a tree of objects which are HTML elements. The image below gives a better idea.
With the use of the DOM, you can do a bunch of useful things on the webpage like:
15
creating new events for synthetic user events
Getting Started,
We will build a simple colour guessing game. Every time the game is started, a
random RGB colour code will be selected. Depending on the mode of the game, we will have
three (easy) or six (hard) options or colour blocks on the screen to choose from. Every time an
incorrect colour block is selected, the block will disappear until the user selects the correct
colour (or its the last option left).
-Part 1
We’ll start by creating a simple web boiler plate, which will be compromised of index.html,
app.css, and app.js files.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Color Game</title>
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<h1>The Great<br>
<span id="colorDisplay">RGB</span><br>
Color Game
</h1>
<div id="stripe">
<button id="reset">New Colors</button>
<span id="message"></span>
<button class="mode">Easy</button>
<button class="mode selected">Hard</button>
</div>
<div id="container">
<div class="square"></div>
<div class="square"></div>
16
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
This is as simple as it gets. We can simply segregate the entire webpage in three
primary blocks.
First we have the header section, which has the text and may contain some other
information if you want to add it in there.
Next is the control panel, which has buttons to reset the game and to switch between
the game modes.
Third — and the most interesting part — is the main game area, which has six divs.
These divs serve as the options for every random RGB colour code which can be
selected by some logic.
app.css
body {
background-color: #232323;
margin: 0;
font-family: "Montserrat", "Avenair";
}
h1 {
text-align: centre;
line-height: 1.1;
font-weight: normal;
17
color: white;
background: steel blue;
margin: 0;
text-transform: uppercase;
padding: 20px 0;
}
#container {
margin: 20px auto;
max-width: 600px;
}
.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
border-radius: 15%;
transition: background 0.6s;
-webkit-transition: background 0.6s;
-moz-transition: background 0.6s;
}
Some basic styles have been added for the body, text, and squares that serve as the
game options.
. app.js
var numSquares = 6;
var colors = [];
var pickedColor;
var squares = document.querySelectorAll(".square");
var resetButton = document.querySelector("#reset");
var modeButtons = document.querySelectorAll(".mode");
18
We have stored all the HTML elements in the form of variables. This will help us
perform some actions by adding events to each of these variables, and by calling them
inside various logic functions we will create during this article.
In fact, let’s break each of these variables down and see what their significance is:
The numSquares variable stores the number of squares that will be available in
the game as per the mode. For simplicity’s sake, I have hard coded the value to be
six always — we can come back to this and add some logic to keep it changing.
colors are an empty array which contains the random six or three RGB color
code generated every time the game is reset, or the mode is changed.
pickedColor is the color/option block selected by the user upon every click.
squares are an array of all the squares on the page that are available as options.
This array may have three or six elements depending on the mode of the game.
The reset variable is the “new game” button in the control panel.
modeButtons is again an array which has easy and hard mode buttons in it.
If you have followed up to this point, here you should have a pretty basic version of
this game. You may open the index.html file in any browser and check it out. All right,
so now that we have the ground set, let’s get to the serious stuff.
-Part 2
In this section, we will mostly be working with the JavaScript file and a few times with
the CSS file.
19
Our first goal will be generating random colors every time the game is started or
restarted, or the mode is changed. Let’s see how can do that.To understand the
underlying principle of generating anything randomly, we should start with a hard-
coded array of six RGB color codes. Let’s try to set those colors as the background
colors of the six squares/options available on the webpage.
var colors = [
"rgb (255, 0, 0)",
"rgb(255, 0, 255)",
"rgb(255, 225, 0)",
"rgb(255, 0, 255)",
"rgb(0, 255, 255)",
"rgb(0, 255, 0)"
];
var squares = document. querySelectorAll(. squares);
for (i=0; i<squares.length; i++) {
squares.style.backgroundColor = colors[i]
}
I used the already created squares array to run a loop across all the squares present in the
array.
I matched the background color of each square to its corresponding index in the colors
array.
If you add this to the app.js file and you refresh the browser, you will see that each square is
now a unique color.
20
*screenshot from the browser
You might notice that the buttons are not yet styled but leave that for now. We will come to
that part later.
So, all we need is event listeners enabled on each option/color block listening for click
events. The easiest way to do that is — again you guessed it right — by looping through the
array of squares. This loop would look like that which was used to style the background of the
color blocks. Let’s look at the code:
Now every time you click on any block you will get this alert message from the
browser. That was easy! Now our options are receptive, and they are responding to user input.
All we need to do now is define the logic that tells what happens if the color picked by the
game and that chosen by the user are the same. By now you may already have the solution if
you have paid attention to the above parts carefully. So, let’s see how we can do it.
21
Checking if the color is correct or not
Let’s explore the possibilities we have with our options/color boxes being receptive
and responding back. We can conduct a small test and see if the two colors match or not. Very
soon we will have randomly generated colors every time we refresh the page or every time we
reset the game or change the mode of game. But for now, we will practice with the set of six
RGB color codes we have assigned in the file.
Let’s look at some code and then I would break it down for you.
pickedColor = colors[3];
22
this.style.backgroundColor = "#232323";
messageDisplay.text = "Wrong Choice!";
}
})
};
We start with defining what the default color picked by the game will be, with the
variable pickedColour.
Then we run us for loop which lets us go through the array of color blocks/options.
Then we enable the click events on every color bock/option. We do this using a callback
function. This function does nothing but select the background color of the selected color
block/option simply by assigning it to the variable called clickedColour.
Now we have both colors: one that was selected by the game and the other by the user.
All that’s left is to match and see if the choice was correct or not.
We can do this easily using the if else block. If the choice is correct, then do this, or else
do something else.
If the correct color is selected, we add some text on the page to confirm the correct choice
and add some visual effect to reconfirm. Else we match the color of that particular color
option/block to match the background color of the page. This produces an effect as if the
color block/option just disappeared.
Now you have seen that if the same color is selected, then a function is executed. Let’s see
what that function is made up of:
function changeColors(color) {
for (i=0; i <= squares. length; i++) {
squares[i].style.backgroundColor = color;
messageDisplay.text = "You are good at guessing!";
}
}
23
This function goes through the array of color blocks/options and resets the background color
to be that of the selected color or the default color.
In case the colors are not the same, we simply set the current selection’s background color to
be that of the webpage.
else {
this. Style. backgrounds = "#232323";
messageDisplay.text = "Wrong Choice!";
}
Alright now that we have the main game set, we just need to worry about minimal design
issues and adding the functionality into the control panel.
But first let’s look at what the code folder looks like at this point if you have followed all the
steps correctly:
index.html
<!DOCTYPE
html>
<html>
<head>
24
<title>Color Game</title>
<link rel="stylesheet" type="text/css" href="app.css">
</head>
<body>
<h1>
The Great
<br>
<span id="colorDisplay">RGB</span>
<br>
Color Game
</h1>
<div id="stripe">
<button id="reset">New Colors</button>
<span id="message"></span>
<button class="mode">Easy</button>
<button class="mode selected">Hard</button>
</div>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
app.css
body
{
background-color: #232323;
25
margin: 0;
font-family: "Montserrat", "Avenair";
}
h1 {
text-align centre;
line-height: 1.1;
font-weight: normal;
color: white;
background: steel blue;
margin: 0;
text-transform: uppercase;
padding: 20px 0;
}
#container {
margin: 20px auto;
max-width: 600px;
}
. square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
border-radius: 15%;
transition: background 0.6s;
-webkit-transition: background 0.6s;
-moz-transition: background 0.6s;
}
app.js
26
Var numSquares=6;
var pickedColor;
var squares = document. querySelectorAll(".square");
var messageDisplay = document. query Selector("#message");
var resetButton = document. query Selector("#reset");
var modeButtons = document. querySelectorAll(".mode");
var colors = [
"rgb (255, 0, 0)",
"rgb (0, 255, 0)",
"rgb (0, 0, 255)",
"rgb (255, 255, 0)",
"rgb (255, 0, 255)",
"rgb (0, 255, 255)"
];
pickedColor = colors [3];
for (i=0; i<squares. length; i++) {
//apply background colour to all the squares...
squares[i]. style.backgroundColor = colors[i]
//enable click event on each square....
squares[i]. addEventListener('click', function() {
//if the user selected the right colour....
var clickedColor = this. style.backgroundColor;
//check if the selected colour matches the default colour...
if (pickedColor === clickedColor) {
changeColors(pickedColor);
messageDisplay.text = "You are good at guessing!";
}
27
})
};
function changeColors(color) {
for (i=0; i<=squares. length; I++) {
squares[i]. style. backgroundColor = color;
}}
Part 3
All is well. But now we need to create new randomly generated RGB color codes in
our game that are not the same set of colours that would be assigned in the color
blocks/options.
If that makes you think about functions, then that’s the right choice. We will be
creating a new function along with totally random (new) color codes, and we will assign them
to the colors array. Then we’ll fetch them in the color blocks/options array.
Let’s see what the code looks like, and then we’ll go through it line by line.
function
randomColor
() {
//pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
//pick a "green" from 0 -255
var g = Math.floor(Math.random() * 256);
//pick a "blue" from 0 -255
var b = Math.floor(Math.random() * 256);
return "rgb (" + r + ", " + g + ", " + b + ")";
}
A built-in method in JavaScript helps us generate a random number between 0 and 1. Then we
make some manipulations to make sure that the range of that random number stays between
the digits 0 and 255.
28
First, we implement Math.random, selecting any random number between 0 and 1, then
multiply the number by 256 since we don’t want the number to be any bigger than 255.
Once we have a random number, we use Math.floor and make sure that we only have the
digit before the decimal values (a whole number).
We assign these random numbers generated to variables called r, g, and b. Each signifies
its own respective RGB number for the color code.
Lastly, we add up all of these numbers or variables to form a string. We return the string,
so it looks something like this: rgb(23, 45, 112).
All that’s left to do is to run this function depending on the mode of the game and
generate three or six random RGB color codes and assign them in the colors array.
But this will only return a string which looks like an RGB code. How will this be added to the
array of colors we have? How will a random color be selected every time the game is started
or reset?
To accomplish both things, we’ll create a couple of more functions and see how they help us
solve this issue.
To do this, we will create a new function called pickColor (). Let’s see how the function will
look, and then we will break it down.
function pickColor () {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}
As simple as it can get, let’s see what these two powerful lines do for us.
29
As we have already seen with the magic of Math.random and Math.floor, we
use the same function to get a random number generated between 0 and the
length of the array.
Next, we get the corresponding RGB code in the colors array by using the random
number in the index
Add six (or three) random RGB codes in the colors array
30
Every time this loop gets executed, a new RGB code is pushed into the array created
Now after all these new functions and all this code manipulation, our code base for app.js has
changed quite a bit. Let’s see what it looks like now:
var numSquares=6;
var pickedColor;
var squares = document. querySelectorAll(".square");
var systemMessageDisplay = document. querySelector("#default-
code");
var userMessageDisplay = document. querySelector("#user-code");
var resetButton = document. querySelector("#reset");
var modeButtons = document. querySelectorAll(".mode");
var header = document. querySelector('#header');
var colors = generateRandomColors (6);
pickedColor = pickColor ();
systemMessageDisplay.innerHTML = pickedColor;
for (i=0; i<squares. length; i++) {
//apply background colour to all the squares...
squares[i]. style.backgroundColor = colors[i]
//enable click event on each square....
squares[i]. addEventListener('click', function() {
//show user the current value....
31
//if the user selected wrong colour....
else {
this. style.backgroundColor = "#232323";
messageDisplay.text = "Wrong Choice!";
}
})
};
function changeColors(color) {
for (i=0; i<=squares. length; i++) {
squares[i]. style.backgroundColor = color;
}
}
function pickColor () {
var random = Math.floor(Math.random() * colors. length);
console.log("pickColor");
return colors[random];
}
function randomColors () {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb (" + r + ", " + b + ", " + g + ")";
}
function generateRandomColors(num) {
var arr = [];
for (i=0; i < num; i++) {
arr. push(randomColors());
}
return arr;
}
32
Reset Game
After almost setting up the primary logic, this may look like a cake walk. It’s all about
creating a function and letting that function do its job against any given user input (in this
case, a click of the reset button).
function reset () {
//create a new array of 6 random colors
//pick new random color
//fill the squares with new set of generated colors
}
I strongly recommend writing pseudo code while solving complex problems. This habit of
writing pseudo code has helped me save a lot of time whenever I’m stuck on complex
algorithmic challenges.
Alright, coming back to our reset button let’s see how the actual function would look:
function reset () {
//create a new array of 6 random colors
//pick new random colour
//fill the squares with new set of generated colours
}
33
We start with adding the event listener for the reset button. We then fire a callback
function which does a bunch of things when the click event is fired.
When it’s fired, we start by generating a new array of six random colors.
Lastly, we reset the background color for all the color blocks.
This is what the updated app.js looks like after all the edits we have made:
Var numSquares=6;
var pickedColor;
var squares = document. querySelectorAll(".square");
var systemMessageDisplay = document. querySelector("#default-
code");
34
//apply background colour to all the squares...
squares[i]. style.backgroundColor = colors[i]
//enable click event on each square....
squares[i]. addEventListener('click', function() {
//show user the current value....
userMessageDisplay.innerHTML = this. style.backgroundColor;
//if the user selected the right colour....
var clickedColor = this. style.backgroundColor;
//check if the selected colour matches the default colour...
if (pickedColor === clickedColor) {
header. style.backgroundColor = pickedColor;
changeColors(pickedColor);
}
//if the user selected wrong colour....
else {
this. style.backgroundColor = "#232323";
messageDisplay.text = "Wrong Choice!";
}
})
};
function changeColors(color) {
for (i=0; i<=squares. length;i++) {
squares[i]. style.backgroundColor = color;
}
}
function pickColor () {
var random = Math.floor(Math.random() * colors. length);
console.log("pickColor");
return colors[random];
}
function randomColors () {
35
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb (" + r + ", " + b + ", " + g + ")";
}
function generateRandomColors(num) {
var arr = [];
for (i=0; i < num; i++) {
arr. push(randomColors());
}
return arr;
}
36
CHAPTER 5
CONCLUSION
JavaScript is a wonderful technology to use on the web. It is not that hard to learn, and
it is very versatile. It plays nicely with other web technologies — such as HTML and CSS —
and can even interact with plugins such as Flash. JavaScript allows us to build highly
responsive user interfaces, prevent frustrating page reloads, and even fix support issues for
CSS. Using the right browser add-ons (such as Google Gears or Yahoo Browser Plus) you can
even use JavaScript to make online systems available offline and sync automatically once the
computer goes online.
JavaScript is also not restricted to browsers. The speed and small memory footprint of
JavaScript in comparison to other languages brings up more and more uses for it — from
automating repetitive tasks in programs like Illustrator, up to using it as a server-side language
with a standalone parser. The future is wide open.
37
BIBLIOGRAPHY
https://en.wikipedia.org/wiki/JavaScript
https://www.w3schools.com/js/
https://skillcrush.com/2018/06/18/projects-you-can-do-
with-javascript/
38