You are on page 1of 44

A Certification Course Report

on
Introduction to Programming using JavaScript

Submitted in partial fulfillment of requirement for the award of degree of

BACHELOR OF TECHNOLOGY
In
ELECTRONICS AND COMMUNICATION ENGINEERING
By
MALINENI DEEKSHA
(15K41A0494)
SR ENGINEERING COLLEGE

CERTIFICATE

This is to certify that this Certification course entitled “Introduction to


Programming using JavaScript” is a bonafide work carried out by Ms. MALINENI
DEEKSHA (15K41A0494), in partial fulfillment of the requirements for the award of the
degree of Bachelor of Technology in Electronics and Communication Engineering during
the academic year 2018-2019 under our guidance and supervision.

Ms.P. ANJALI Dr. J.TARUN KUMAR


Assistant Professor, Professor & HOD,
SR Engineering College, SR Engineering College,
Ananthasagar, Warangal. Ananthasagar, Warangal.
ACKNOWLEDGEMENT

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.

I express my gratitude to MICROSOFT TECHNOLOGY ASSOCIATE for their guidance


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

Student will be able to

 Understand the fundamentals of HTML5,CSS3 and JavaScript.


 Build the User Interface by using HTML5.
 Choose and configure HTML5 tags such that to display text, graphics, play media,
organize contents and forms and also for input and validation.
 Format the User Interface by Using CSS3.
 Arrange UI content by using CSS3.
 Manage the graphical interface by using CSS3.
 Code animations by using JavaScript.
 Code server-side programming (Jquery).introductory JavaScript skills.

iv
CONTENTS

Acknowledgement iii
Objective iv
List of Acronyms vi

Chapter No. Title Page No.

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

3 OUTCOME OF THE COURSE


3.1 Outcome of the course 14
4 CASE STUDY OF CERTIFICATION
4.1 Part 1 16
4.2 Part 2 20
4.1 Part 3 28
5 CONCLUSION
5.1 Conclusion 37

BIBLIOGRAPHY 38

v
LIST OF ACRONYMS

ACRONYMS ABBREVATIONS
MTA Microsoft Technology Associate

UI User Interface

HTML Hyper Text Markup Language

CSS Cascading Style Sheets

OOP Object Oriented Programming

DOM Document Object Model

BOM Browser Object Model

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.

In simple words, JavaScript is a scripting language that allows you to implement


Complex things on web pages. So basically every browser, every PC ,every mobile
understand JavaScript. It is like a Universal language.

JavaScript is a programming language that can be included on web pages to make


them more interactive. You can use it to check or modify the contents of forms, change
images, open new windows and write dynamic page content. You can even use it with CSS to
make DHTML (Dynamic HyperText Markup Language). This allows you to make parts of
your web pages appear or disappear or move around on the page. JavaScript only execute on
the page(s) that are on your browser window at any set time. When the user stops viewing
that page, any scripts that were running on it are immediately stopped. The only exceptions
are cookies or various client-side storage APIs, which can be used by many pages to store
and pass information between them, even after the pages have been closed. Before we go any
further, let me say; JavaScript has nothing to do with Java. If we are honest, JavaScript,
originally nicknamed Livewires and then Live Script when it was created by Netscape,
should in fact be called ECMAScript as it was renamed when Netscape passed it to the
ECMA for standardization. JavaScript is a client side, interpreted, object oriented, high level
scripting language, while Java is a client side, compiled, object-oriented high-level language.
-Client side
Programs are passed to the computer that the browser is on, and that computer runs
them. The alternative is server side, where the program is run on the server and only the
results are passed to the computer that the browser is on. Examples of this would be PHP,
Perl, ASP, JSP etc.
1
-Interpreted
The program is passed as source code with all the programming language visible. It is
then converted into machine code as it is being used. Compiled languages are converted into
machine code first then passed around, so you never get to see the original programming
language. Java is actually dual half compiled, meaning it is half compiled (to 'byte code')
before it is passed, then executed in a virtual machine which converts it to fully compiled
code just before use, in order to execute it on the computer's processor. Interpreted languages
are generally less fussy about syntax and if you have made mistakes in a part they never use,
the mistake usually will not cause you any problems.
-Scripting
This is a little harder to define. Scripting languages are often used for performing
repetitive tasks. Although they may be complete programming languages, they do not usually
go into the depths of complex programs, such as thread and memory management. They may
use another program to do the work and simply tell it what to do. They often do not create
their own user interfaces, and instead will rely on the other programs to create an interface for
them. This is quite accurate for JavaScript. We do not have to tell the browser exactly what to
put on the screen for every pixel (though there is a relatively new API known as canvas that
makes this possible if needed), we just tell it that we want it to change the document, and it
does it. The browser will also take care of the memory management and thread management,
leaving JavaScript free to get on with the things it wants to do.
-High level
Written in words that are as close to English as possible. The contrast would be with
assembly code, where each command can be directly translated into machine code.
Object oriented programming:
-Objects
An object is a 'thing'. For example, a number is an object. An array is an object. Your
browser window is an object. A form in your document is an object. There are hundreds
more, and in some cases, you can create your own.
Objects can have objects in them. For example, your document can have a form in it.
This form is a 'child object' of the document. Therefore, the document is the 'parent object' of
the form. To reference the child object, we must go through the parent object , e.g.
document.myForm

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

provided by the class 'object'.


Classes are not so important in JavaScript as they are in many other object-oriented
programming languages. Classes can be created when you define your own classes of objects,
but it is not usual to create your own 'sub'-classes.
-Collections
If you need to know what arrays are, see the section on Variables.There are many
arrays that are inbuilt into each document. The document itself is an array in certain uses. The
most obvious of these collections is the images collection. To refer to images in the
document, we use document.images['name of image'].This is a special kind of array, known
as a collection.
-Properties
Take, for example, an image. When we define images in HTML, we write:

<img src="frog.gif" name="myImage" height="10" width="10" alt="A fro g">

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?

There are at least three great things about JavaScript:


 Full integration with HTML/CSS.

 Simple things done simply.

 Supported by all major browsers and enabled by default.

How to Run JavaScript?

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.

Tools You Need


To start with, you need a text editor to write your code and a browser to display the
web pages you develop. You can use a text editor of your choice including Notepad++,
Visual Studio Code, Sublime Text, Atom or any other text editor you are comfortable with.
You can use any web browser including Google Chrome, Firefox, Microsoft Edge, Internet
Explorer etc.

How Is JavaScript Constructed?

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.

As an example, think of the following situation. A person clicks a submit button on a


form. When they click the button, we want to check if they have filled out their name in a text
box and if they have, we want to submit the form. So, we tell the form to detect the submit
event. When the event is triggered, we tell it to run the function that holds together the tests
and actions. The function contains a control structure that uses a comparison operator to test
the text box to see that it is not empty. Of course, we must work out how to reference the text
box first. The text box is an object. One of the variables it holds is the text that is written in
the text box. The text written in it is a literal. If the text box is not empty, a method is used
that submits the form.

Adding A Script to The Page

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">

//JavaScript goes here

</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>

<p>This will not be displayed if JavaScript is enabled</p>

</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 single line comment

/* This is a

block comment */

7
</script>

Using External Script Files

You can also use a separate header file to contain the JavaScript (usually *.js) making
it easy to share across pages:

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

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

- subtracts the second number from the first

/ divides the first number by the second

* multiplies two numbers

% divide the first number by the second and return the remainder

= assigns the value on the right to the object on the left

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

++ increment the number

-- decrement the number

== the numbers or objects or values must be equal

!= the numbers or objects or values must not be equal

<< bitwise left shift

>> bitwise right shift

& bitwise AND

| bitwise OR

^ bitwise XOR

~ bitwise NOT

! logical NOT (the statement must not be true)

&& logical AND (both statements must be true)

|| logical OR (either statement must be true)

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

If you ask JavaScript to perform a calculation using multiple operators, those


operators will be evaluated in a specific order. The order in which these are evaluated is: * /
% + - + (where the second + is appending strings). To change the order in which they are
calculated, use parenthesis ( ) as the contents of parenthesis are calculated before the contents
outside the parenthesis.

The Math Object Methods

9
Math object methods

Operator What it does

Math.abs(n) Returns the absolute value of n

Math.acos(n) Returns (in radians) cos-1 of n

Math.asin(n) Returns (in radians) sin-1 of n

Math.atan(n) Returns (in radians) tan-1 of n

Math.atan2(n, k) Returns the angle (rads) from cartesian coordinates 0,0 to n,k

Math.ceil(n) Returns n rounded up to the nearest whole number

Math.cos(n) Returns cos n (where n is in radians)

Math.exp(n) Returns en

Math.floor(n) Returns n rounded down to the nearest whole number

Returns ln(n)
Math.log(n)
Note, to find log10(n), use Math.log(n) / Math.log(10)

Math.max(a,b,c,...) Returns the largest number

Math.min(a,b,c,...) Returns the smallest number

Math.pow(n,k) Returns nk

Math.random() Returns a random number between 0 and 1

Math.round(n) Returns n rounded up or down to the nearest whole number

Math.sin(n) Returns sin n (where n is in radians)

Math.sqrt(n) Returns the square root of n

Math.tan(n) Returns tan n (where n is in radians)

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

'a' or '@' or 'k' etc.

-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.

-Float (or double)

23.546 or -10.46

-Boolean

true or false

-Function

A function; see the section on Functions

-Object

An object; see the section on Object oriented programming

-Array

A type of object that can store variables in cells (see below)

-Regular Expression

A pattern that can be used to match strings or substrings

-Undefined

A variable that has not been given a value yet

-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.

Special String Characters


There are a few string characters that can be escaped with a backslash and can be used
to replace untypeable characters. These are:

11
\n

A newline character. Use this if you want to insert a line break into text.

\f

A form feed. Try not to use this ever. Use \n instead.

\r

A carriage return. Try not to use this ever. Use \n instead.

\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

Certain methods, like the stringObject.replace() and stringObject.match() methods,


can recognise patterns in text. To do this, they use regular expressions. These are well
documented elsewhere so I will not describe the syntax here. Basically, what you can do is
use special characters to recognise text patterns (like \w for characters a-z, A-Z, 0-9 and _).
To define a collection of characters as a regular expression,you use the / character
(sometimes with a g or i after it). For example, the regular expression /\/\*[\w\W]*\*\//
matches block comments.

Some rare browsers do not support regular expressions. In theory, you should be able
to detect regular expression support using this:

if( window.RegExp ) { var myRegularExpression = new RegExp("pattern"); }

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.

Functions are defined using one of these constructs:

Normal function construct

function nameOfFunction(listOfVariableNames) {

function code should be written here}

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.

Map HTML using the DOM - Document Object Model.

Identify popular JavaScript Libraries.

Create dynamic styles.

Create animation on a web page.

Use regular expressions for form validation.

Debug using firebug.

Create an XMLHttpRequest Object

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.

Fig 4.1 Block diagram of DOM

With the use of the DOM, you can do a bunch of useful things on the webpage like:

 adding and deleting HTML elements and attributes

 adding and deleting CSS rules on a user fired event

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.

Generating random colours

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 added six static RGB color codes to the color array

 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.

Enable Click Functionality

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:

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


squares[i].addeventListeners('click', function() {
alert('option was clicked');
});
}

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.

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


squares[i].addeventListeners('click', function() {
//if correct block is clicked do something....
//if wrong block is clicked do something....
});
}

As you already may know, we will be using a simple if-else block.

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);
}
//if the user user selected wrong colour....
else {

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!";
}

//if the user user selected wrong colour....


else {
this. style.backgroundColor = "#232323";
messageDisplay.text = "Wrong Choice!";
}

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.

Select a random colour from the array

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

To do this, we use the above two functions, which are randomColors


() and pickColors (). What the randomColors () function does is that it runs the
randomColors() function six or three times (depending on the mode of the game) and adds the
corresponding number of RGB color codes to the colors array. We will name this
generateRandomColor(num*) function. Let’s see how the code looks and break it down line
by line.

*num will be decided based on the mode of the game.


function
generateRandomColor(num)
{
//make an array
var arr = [];
// run the randomColor function num times
for (i=0; i < num; i++) {
arr. push(randomColors());
}
// return an array
return arr;
}

 First, we’ll make a simple empty array

 Next, we run a loop as per the mode of the game

30
 Every time this loop gets executed, a new RGB code is pushed into the array created

 At last we return this array

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....

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);
}

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).

All we want with the reset button is

 generate a set of six random colors

 pick a random color out of the new created colors array.

Let’s see how the pseudo code would look:

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
}

Let’s break it down line by line:

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.

 Then we pick a random color.

 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");

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);
Picked Color = pickColor ();
// Reset Game...
resetButton.addEventListener('click', function (){
colors = generateRandomColors (6);
pickedColor = pickColor ();
systemMessageDisplay.innerHTML = pickedColor;
header. style.backgroundColor = 'steel blue';
userMessageDisplay.innerHTML = '';
for (i=0; i<=squares.length; i++) {
squares[i]. style.backgroundColor = colors[i];
}
})
systemMessageDisplay.innerHTML = pickedColor;
for (i=0; i<squares. length; i++) {

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

You might also like