0% found this document useful (0 votes)
1 views49 pages

Ephrem__Tesfaye__IP-I__Chapter__Four__Note__&__Question (2)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views49 pages

Ephrem__Tesfaye__IP-I__Chapter__Four__Note__&__Question (2)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Internet Programming I Chapter Four – JS Basics

College of Engineering, Technology and Computational Sciences


Department of Computer Science

Course Title: Internet Programming I (COSC 3031)


Topic: JavaScript Basics

Topic Contents

4. JavaScript Basics
4.1 Client side scripting and its advantage
4.2 Advantages and limitations of JavaScript
4.3 JavaScript basic syntax
4.4 Flow control in JavaScript
4.5 Event handler in JavaScript
Objectives
After studying this chapter, you should be able to:
 Discuss what scripting language is and differentiate it from programming languages
 Understand what client side scripting is and use JS as a client side scripting language
 Understand the basic syntax of JS
 Solve different programming problems using JS and develop algorithmic thinking
 Manipulate the DOM
 Handle user events and respond appropriately for the user’s actions

Compiled By: Ephrem Tesfaye Tsidu 1


Internet Programming I Chapter Four – JS Basics

4.1 Client side scripting and its advantage


A script or scripting language is a computer language that does not need the compilation step and
is rather interpreted one by one at runtime. It is where the script is written and where instructions
for a run-time environment are written. In contrast to programming languages that are compiled
first before running, scripting languages do not compile the file and execute the file without being
compiled.
 Programming language is a language with set of rules to instruct a computer or computing
device to perform specific tasks. It is with the use of machine language that we can instruct
a computer to do tasks. Machine language gives instructions as 0’s and 1’s.
 Scripting languages are programming languages that do not need an additional step to be
converted to a language a machine or computer understand because they are written to just
communicate with one software, not with a machine/computer. For example, JavaScript
was originally developed to only communicate with web browsers. It is the web browsers
that directly communicate with the processor. Because JavaScript needs only to instruct
the browser, it originally didn’t need a compiler that converts it to the machine code. It
only needed an interpreter to be understood by the browser.
Application of Scripting Languages
There are several areas where scripting languages are used:
 Scripting languages are used on the server-side as well as the client-side and are also widely
used in web applications. The languages like Python, PHP, and Perl are examples of server-
side scripting languages, and JavaScript, AJAX are examples of client-side scripting
languages.
 Like Python scripts, Perl, Shell is all the scripting languages, which are used in system
administration.
 It is used to construct plugins and extensions for current applications, as well as in games
and multimedia.
Advantages of scripting languages
Easy learning: In order to learn scripting languages, there is not much need for the
knowledge of web technology. Therefore, these languages enable users to learn code
quickly.

Compiled By: Ephrem Tesfaye Tsidu 2


Internet Programming I Chapter Four – JS Basics

Fast editing: It is particularly efficient since it uses a small amount of data structures and
variables.
Interactivity: It helps to make web pages more interactive by adding combinations and
visualization interfaces. The use of scripting languages is demanded by modern web pages.
It includes background and foreground colors and so on, which helps to create enhanced
web pages.
Functionality: Scripting languages contain different libraries, which help to create new
applications in web browsers. They are different from normal programming languages.
Types of Scripting Languages
There are two main types of scripting languages: server-side and client-side. They differ on where
the code is run from, which affects not only the actual languages chosen but also the performance
and their capabilities.
 Server-side scripting language
The term server-side scripting language refers to those that run off a web server. Since it performs
from the back-end side, the script is not visible to the visitor. Because of that, it is a more secure
approach.
They are often used to create dynamic websites and platforms, handle user queries, and generate
and provide data and others. A famous example of server-side scripting is the use of PHP in
WordPress.
Examples: PHP, Python, Node.js, Perl, and Ruby.
 Client-side scripting language
Unlike the above, client-side scripting languages run off the user’s browser. It is usually performed
at the front end, which makes it visible to visitors and makes it less vulnerable to exploits and
leaks. As such, it is often used to build user interfaces and lighter functionality such as that.
Since it runs locally, they usually provide better performance and, therefore, do not strain your
server.
Examples: JavaScript.
Client-side scripting generates code that may be executed on the client end without needing server-
side processing. These scripts are typically embedded into HTML text. Client-side scripting may

Compiled By: Ephrem Tesfaye Tsidu 3


Internet Programming I Chapter Four – JS Basics

be utilized to check the user's form for problems before submitting it and to change the content
based on the user input.
Client-side scripting is mostly utilized to create dynamic user interface elements like pull-down
menus and animation buttons, navigation tools, data validation, and more. Nowadays, it is
increasing and evolving every day. This means that writing web programming for clients is now
much easier and quicker and, in turn, reduces the load on servers.
Application of Client-side Scripting-
Client-side scripting can be utilized to make websites more interactive. It is typically used at the
front end, which is where users can view the web page using the browser. The most important
functions of scripting on the client side are listed below:
 To retrieve information from a web browser or the user's screen.
 Used in the context of online games.
 To personalize the web page without having to load it again.
 Client-side scripting can be used to verify credentials. If the user has entered incorrect
details when logging in, the web page will display an error message on the user's machine
and will not submit data to the website server.
 To create ads that engage with users rather than just display pictures.
 Create animated images that change as we move our mouse across them.
 Client-side scripts can be used to check for installed plugins and notify the user that the
plugin is needed.

Compiled By: Ephrem Tesfaye Tsidu 4


Internet Programming I Chapter Four – JS Basics

4.2 JavaScript, it’s advantages and limitations


JavaScript is a lightweight but incredibly powerful scripting language. We most frequently
encounter it through our browsers, but JavaScript has snuck into everything from native
applications to PDFs to ebooks. Even web servers themselves can be powered by JavaScript.
JavaScript is also loosely typed. All this means is that we don’t necessarily have to tell JavaScript
what a variable is. If we’re setting a variable to a value of 5, we don’t have to programmatically
specify that variable as a number. As you may have noted, 5 is already a number, and JavaScript
recognizes it as such.
Most commonly we’ll encounter JavaScript as a way to add interactivity to a page. Where the
“structural” layer of a page is our markup and the “presentational” layer of a page is made up of
CSS, the third “behavioral” layer is made up of our JavaScript. All of the elements, attributes, and
text on a web page can be accessed by scripts using the DOM (Document Object Model).

You’ve likely seen this in action if you’ve ever attempted to register for a website, entered a
username, and immediately received feedback that the username you’ve entered is already taken
by someone. The red border around the text input and the appearance of the “sorry, this username
is already in use” message are examples of JavaScript altering the contents of the page, and
blocking the form submission is an example of JavaScript altering the browser’s default behavior.

Compiled By: Ephrem Tesfaye Tsidu 5


Internet Programming I Chapter Four – JS Basics

In short, JavaScript allows you to create highly responsive interfaces that improve the user
experience and provide dynamic functionality, without waiting for the server to load up a new
page. For example, we can use JavaScript to do any of the following:
Suggest the complete term a user might be entering in a search box as he types. You can
see this in action on Google.com
Show and hide content based on a user clicking on a link or heading, to create a
“collapsible” content area
Both advantages and disadvantages apply to JavaScript. A client's browser is frequently used to
execute JavaScript directly. Similar advantages to server-side languages are also possible for
JavaScript.
Following are the advantages of JavaScript
Simple − JavaScript is simple to comprehend and pick up. Both users and developers will find the
structure to be straightforward. Additionally, it is very doable to implement, saving web developers
a tonne of money when creating dynamic content.
Speed − JavaScript is a "interpreted" language, it cuts down on the time needed for compilation in
other programming languages like Java. Another client-side script is JavaScript, which accelerates
programme execution by eliminating the wait time for server connections. No matter where
JavaScript is hosted, it is always run in a client environment to reduce bandwidth usage and speed
up execution.
Interoperability − Because JavaScript seamlessly integrates with other programming languages,
many developers favour using it to create a variety of applications. Any webpage or the script of
another programming language can contain it.
Server Load − Data validation can be done within the browser itself rather than being forwarded
to the server because JavaScript is client-side. The entire website does not need to be reloaded in
the event of any discrepancy. Only the chosen area of the page is updated by the browser.
Following are the disadvantages of JavaScript
Cannot Debug − Although some HTML editors allow for debugging, they are not as effective as
editors for C or C++. Additionally, the developer has a difficult time figuring out the issue because
the browser doesn't display any errors.

Compiled By: Ephrem Tesfaye Tsidu 6


Internet Programming I Chapter Four – JS Basics

Unexpected stop of rendering − The website's entire JavaScript code can stop rendering due to a
single error in the code. It appears to the user as though JavaScript is absent. The browsers,
however, are very forgiving of these mistakes.
Client-side Security − The user can see the JavaScript code; it could be misused by others. These
actions might involve using the source code anonymously. Additionally, it is very simple to insert
code into the website that impair the security of data transmitted via the website.
Inheritance − JavaScript does not support multiple inheritance; only one inheritance is supported.
This property of object-oriented languages might be necessary for some programmes.
Browser Support − Depending on the browser, JavaScript is interpreted differently. Therefore,
before publication, the code needs to run on various platforms. We also need to check the older
browsers because some new functions are not supported by them.
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
Including JavaScript code inline:
Insert your JavaScript code directly inside the HTML tag using the special tag attributes such as
onclick, onmouseover, onkeypress, onload, etc.
<body>
<button onclick="alert('Hello World!')">Click Me</button>
</body>
Note: You should avoid placing large amount of JavaScript code inline as it clutters up your HTML
with JavaScript and makes your JavaScript code difficult to maintain
To embed a script on a page, just add the code as the content of a script element:
<script>
… JavaScript code goes here
</script>
External scripts
The other method uses the src attribute to point to a script file (with a .js suffix) by its URL. In this
case, the script element has no content.

Compiled By: Ephrem Tesfaye Tsidu 7


Internet Programming I Chapter Four – JS Basics

<script src="my_script.js"></script>
The advantage to external scripts is that you can apply the same script to multiple pages (the same
benefit external style sheets offer).
Script placement
The script element go anywhere in the document, but the most common places for scripts are in
the head of the document and at the very end of the body. It is recommended that you don’t sprinkle
them throughout the document, because they would be difficult to find and maintain.
For most scripts, the end of the document, just before the </body> tag, is the preferred placement
because the browser will be done parsing the document and its DOM structure. Consequently, that
information will be ready and available by the time it gets to the scripts and they can execute faster.
In addition, the script download and execution blocks the rendering of the page, so moving the
script to the bottom improves the perceived performance.

Compiled By: Ephrem Tesfaye Tsidu 8


Internet Programming I Chapter Four – JS Basics

4.3 JavaScript basic syntax


There are a few common syntactical rules that wind their way though all of JavaScript. It is
important to know that JavaScript is case-sensitive. A variable named “myVariable”, a variable
named “myvariable”, and a variable named “MYVariable” will be treated as three different
objects. Also, whitespace such as tabs and spaces are ignored, unless they’re part of a string of text
and enclosed in quotes.
Statements
A script is made up of a series of statements. A statement is a command that tells the browser what
to do. Here is a simple statement that makes the browser display an alert with the phrase “Thank
you.”
alert("Thank you.");
The semicolon at the end of the statement tells JavaScript that it’s the end of the command, just as
a period ends a sentence. According to the JavaScript standard, a line break will also trigger the
end of a command, but it is a best practice to end each statement with a semicolon.
Comments
JavaScript allows you to leave comments that will be ignored at the time the script is executed, so
you can leave reminders and explanations throughout your code. This is especially helpful if this
code is likely to be edited by another developer in the future.
There are two methods of using comments. For single-line comments, use two slash characters (//)
at the beginning of the line. You can put singleline comments on the same line as a statement, as
long as it comes after the statement. It does not need to be closed, as a line break effectively closes
it.
// This is a single-line comment.
Multiple-line comments use the same syntax that you’ve seen in CSS. Everything within the /* */
characters is ignored by the browser. You can use it to “comment out” notes and even chunks of
the script when troubleshooting.
/* This is a multi-line comment. Anything between these sets of characters will be
completely ignored when the script is executed. This form of comment needs to be
closed. */

Compiled By: Ephrem Tesfaye Tsidu 9


Internet Programming I Chapter Four – JS Basics

Variables
A variable is like an information container. You give it a name and then assign it a value, which
can a number, text string, an element in the DOM, or a function—anything, really. This gives us a
convenient way to reference that value later by name. The value itself can be modified and
reassigned in whatever way our scripts’ logic dictates.
The following declaration creates a variable with the name “unity” and assigns it the value 5:
var unity = 5;
We start by declaring the variable using the var keyword. The single equals sign (=) indicates that
we are assigning it a value. Because that’s the end of our statement, we end the line with a
semicolon.
Re-declaring JavaScript variables: If you re-declare a JavaScript variable, it will not lose its
value. In the below example, the variable “width” will still have the value 20 after the execution
of these statements.
var width= "20";
Remember that a variable holds a value, and that value vary. In JavaScript, you can reassign values
to a variable you once declared with var.
When you assign a new value to a variable, you write the variable name, followed by (=) sign and
your new value.
var width = 10; (declaring a variable by the name “width” and assigning the variable
a value of 10)
width = 11; (changing or reassigning value 11 to width variable)
width = 12; (changing or reassigning value 12 to width variable)
Latest variable value always overrides the previous values: At this point, our width variable has a
value of 12 because it is the latest value.
You can use anything you like as a variable name, but make sure it’s a name that will make sense
to you later on. You wouldn’t want to name a variable something like “data”; it should describe
the information it contains. In our very specific example above, “numberFive” might be a more
useful name than “unity.” There are a few rules around variable naming:
 It must start with a letter or an underscore.
 It may contain letters, digits, and underscores in any combination.

Compiled By: Ephrem Tesfaye Tsidu 10


Internet Programming I Chapter Four – JS Basics

 It may not contain character spaces. As an alternative, use underscores in place of spaces
or close up the space and use camel case instead (for example, my_variable or myVariable).
 It may not contain special characters (! . , / \ + * = etc.).
 You can change the value of a variable at any time by re-declaring it anywhere in your
script. Remember: JavaScript is case-sensitive, and so are those variable names.
Data types
The values we assign to variables fall under a few distinct data types.
Undefined
The simplest of these data types is likely “undefined.” If we declare a variable by giving it a name
but no value, that variable contains a value of “undefined.”
var foo;
alert(foo); // This will open a dialog containing "undefined".
Odds are you won’t find a lot of use for this right away, but it’s worthknowing for the sake of
troubleshooting some of the errors you’re likelyto encounter early on in your JavaScript career. If
a variable has a valueof “undefined” when it shouldn’t, you may want to double-check that it
has been declared correctly or that there isn’t a typo in the variable name.
Null
Similar to the above, assigning a variable of “null” (again, case-sensitive) simply says, “Define
this variable, but give it no inherent value.”
var foo = null;
alert(foo); // This will open a dialog containing "null".
Numbers
You can assign variables numeric values.
var foo = 5;
alert(foo); // This will open a dialog containing "5".
The word “foo” now means the exact same thing as the number five as far as JavaScript is
concerned. Because JavaScript is “loosely typed,” we don’t have to tell our script to treat the
variable foo as the number five. The variable behaves the same as the number itself, so you can do
things to it that you would do to any other number using classic mathematical notation: +, -, *, and
/ for plus, minus, multiply, and divide, respectively.

Compiled By: Ephrem Tesfaye Tsidu 11


Internet Programming I Chapter Four – JS Basics

In this example, we use the plus sign (+) to add foo to itself (foo + foo).
var foo = 5;
alert(foo + foo); // This will alert "10".
Strings
Another type of data that can be saved to a variable is a string, which is basically a line of text.
Enclosing characters in a set of single or double quotes indicates that it’s a string, as shown here:
var foo = "five";
alert( foo ); // This will alert "five"
The variable foo is now treated exactly the same as the word “five”. This applies to any
combination of characters: letters, numbers, spaces, and so on. If the value is wrapped in quotation
marks, it will be treated as a string of text. If we were to wrap the number five (5) in quotes and
assign it to a variable, that variable wouldn’t behave as a number; instead, it would behave as a
string of text containing the character “5.”
Earlier we saw the plus (+) sign used to add numbers. When the plus sign is used with strings, it
sticks the strings together (called concatenation) into one long string, as shown in this example.
var foo = "bye"
alert (foo + foo); // This will alert "byebye"
Notice what the alert returns in the following example when we define the value 5 in quotation
marks, treating it as a string instead of a number.
var foo = "5";
alert( foo + foo ); // This will alert "55"
If we concatenate a string and a number, JavaScript will assume that the number should be treated
as a string as well, since the math would be impossible.
var foo = "five";
var bar = 5;
alert( foo + bar ); // This will alert "five5"
Booleans
We can also assign a variable a “true” or “false” value. This is called a Boolean value, and it is the
lynchpin for all manner of advanced logic. Boolean values use the true and false keywords built
into JavaScript, so quotation marks are not necessary.

Compiled By: Ephrem Tesfaye Tsidu 12


Internet Programming I Chapter Four – JS Basics

var foo = true; // The variable "foo" is now true


Just as with numbers, if we were to wrap the value above in quotation marks, we’d be saving the
word “true” to our variable instead of the inherent value of “true” (i.e., “not false”).
In a sense, everything in JavaScript has either an inherently “true” or “false” value. “null”,
“undefined”, “0”, and empty strings (“”) are all inherently false, while every other value is
inherently true. These values, although not identical to the Booleans “true” and “false”, are
commonly referred to as being “truthy” and “falsy.” I promise I didn’t make that up.
Arrays
An array is a group of multiple values (called members) that can be assigned to a single variable.
The values in an array are said to be indexed, meaning you can refer to them by number according
to the order in which they appear in the list. The first member is given the index number 0, the
second is 1, and so on, which is why one almost invariably hears us nerds start counting things at
zero—because that’s how JavaScript counts things, and many other programming languages do
the same. We can avoid a lot of future coding headaches by keeping this in mind.
So, let’s say our script needs all of the variables we defined earlier. We could define them three
times and name them something like foo1, foo2, and so on, or we can store them in an array,
indicated by square brackets ([ ]).
var foo = [5, "five", "5"];
Now anytime you need to access any of those values, you can grab them from the single foo array
by referencing their index number:
alert( foo[0] ); // Alerts "5"
alert( foo[1] ); // Alerts "five"
alert( foo[2] ); // Also alerts "5"
Operators
Assignment operator ( = )
It is used to assign value or change value of a variable.
Example: var x = 10;
Comparison operators

Compiled By: Ephrem Tesfaye Tsidu 13


Internet Programming I Chapter Four – JS Basics

Now that we know how to save values to variables and arrays, the next logical step is knowing
how to compare those values. There is a set of special characters called comparison operators that
evaluate and compare values in different ways:
 == Is equal to
 != Is not equal to
 === Is identical to (equal to and of the same data type)
 !== Is not identical to
 Is greater than
 >= Is greater than or equal to
 < Is less than
 <= Is less than or equal to
There’s a reason all of these definitions read as parts of a statement. In comparing values, we’re
making an assertion, and the goal is to obtain a result that is either inherently true or inherently
false. When we compare two values, JavaScript evaluates the statement and gives us back a
Boolean value depending on whether the statement is true or false.
alert( 5 == 5 ); // This will alert "true"
alert( 5 != 6 ); // This will alert "true"
alert( 5 < 1 ); // This will alert "false"
Equal versus identical
The tricky part is understanding the difference between “equal to” (==) and “identical to” (===).
We already learned that all of these values fall under a certain data type. For example, a string of
“5” and a number 5 are similar, but they’re not quite the same thing. Well, that’s exactly what ===
is meant to check.
alert( "5" == 5 ); // This will alert "true". They're both "5".
alert( "5" === 5 ); // This will alert "false". They're both "5", but they're not the
same data type.
alert( "5" !== 5 ); // This will alert "true", since they're not the same data type.
Even if you have to read it a couple of times, understanding the preceding sentence means you’ve
already begun to adopt the special kind of crazy one needs to be a programmer. Welcome! You’re
in good company.

Compiled By: Ephrem Tesfaye Tsidu 14


Internet Programming I Chapter Four – JS Basics

Mathematical Operators
The other type of operator is a mathematical operator, which performs mathematical functions on
numeric values. We touched briefly on the straightforward mathematical operators for add (+),
subtract (-), multiply (*), and divide (/). There are also some useful shortcuts you should be aware
of:
+= Adds the value to itself
++ Increases the value of a number (or a variable containing a number value) by 1
-- Decreases the value of a number (or a variable containing a number value) by 1
Logical operators
Logical operators are used to determine the logic between variables or values. Logical operators
to perform multiple comparisons. We use these operators when we want to write conditional
statements. We will learn about conditional statements later. For now, let's just focus on the
operators.
There are three logical operators in JavaScript:
 Logical AND (&&): This returns true if both operands are true. Meaning, if either one of
the variables were initialized as false, the && expression would evaluate to false.
true && true = true
true && false = false
false && false = false
false && true = false
(1==1 && 2==2 && 3==7) // returns False
 Logical OR (| |): The OR operator, represented by two pipes, returns true if one operand is
true
true || true = true
true || false = true
false || false = false
false || true = true
(1==1 || 3==2 || 3 == 7) // returns True
 Logical not (!): This returns true if operand is false and vice versa.
! False = True

Compiled By: Ephrem Tesfaye Tsidu 15


Internet Programming I Chapter Four – JS Basics

! True = False
! (1==1 || 3==2) // returns False
NB: Priority order when evaluating JavaScript operators: Priority of operator (operator
precedence) determines the grouping of terms in an expression and decides how an expression is
evaluated.
Example: var x = 2 + 3 * 4; here, x is assigned 14, not 9 because operator * has a higher precedence
than +, so it first gets multiplied with 3*4 and then adds into 2.
The following is a list showing operators that have the highest precedence on top:
 Grouping: ()
 Postfix increment: … ++
 Postfix decrement: … --
 Logical not: !
 Comparison: < , >= , = = = , !=
 Logical AND: &&
 Logical OR: | |
Functions
I’ve introduced you to a few functions already in a sneaky way. Here’s an example of a function
that you might recognize:
alert("I've been a function all along!");
A function is a bit of code that doesn’t run until it is referenced or called. alert() is a function built
into our browser. It’s a block of code that runs only when we explicitly tell it to. In a way, we can
think of a function as a variable that contains logic, in that referencing that variable will run all the
code stored inside it.
All functions share a common pattern. The function name is always immediately followed by a set
of parentheses (no space), then a pair of curly braces that contain their associated code. The
parentheses sometimes contain additional information used by the function called arguments.
Arguments are data that can influence how the function behaves. For example, the alert function
we know so well accepts a string of text as an argument, and uses that information to populate the
resulting dialog.

Compiled By: Ephrem Tesfaye Tsidu 16


Internet Programming I Chapter Four – JS Basics

There are two types of functions: those that come “out-of-the-box” (native JavaScript functions)
and those that you make up yourself (custom functions). Let’s look at each.
Native functions
There are hundreds of predefined functions built into JavaScript, including: alert(), confirm(), and
prompt() These functions trigger browser-level dialog boxes.
 Date() : Returns the current date and time.
 parseInt("123") : This function will, among other things, take a string data type
containing numbers and turn it into a number data type. The string is passed to the function
as an argument.
 setTimeout(functionName, 5000) : Will execute a function after a delay. The function is
specified in the first argument, and the delay is specified in milliseconds in the second (in
the example, 5000 milliseconds equals 5 seconds). There are scores more beyond this, as
well.
JS Built-in Functions
 Mostly Used Javascript Property for array and string
 Length (returns the length of the string/array)
Example:
var a = [1,2,3,4,5];
console.log(a.length);
 Mostly Used Javascript built-in functions for string operations
 charAt() method: It returns the character at the specified index.
Example:

Compiled By: Ephrem Tesfaye Tsidu 17


Internet Programming I Chapter Four – JS Basics

var a = [1,2,3,4,5];
console.log(a.charAt(2)); //displays “3”
 indexOf() method: It returns the index within the calling String object.
 toLowerCase() method: It returns the calling string value converted lower case.
 toUpperCase() method: It returns the calling string value converted to uppercase.
 slice() method: It extracts a session of a string and returns a new string.
 split() method: It splits a string object into an array of strings by separating the
string into the substrings
 Mostly used Javascript functions for array operations
 push() method: Adds new elements to the end of an array, and returns the new array
 pop() method:: Removes an item from the end of an array
 shift() method:: Removes the first element of an array, and returns that element
 unshift() method:: Adds new elements to the beginning of an array, and returns the
new array
 isArray() method:: Returns true if the argument is an array, or false otherwise.
 toString() method: Converts an array to a string, and returns the result
Custom functions
To create a custom function, we type the function keyword followed by a name for the function,
followed by opening and closing parentheses, followed by opening and closing curly brackets.
function name() {
// Our function code goes here.
}
Just as with variables and arrays, the function’s name can be anything you want, but all the same
naming syntax rules apply.
If we were to create a function that just alerts some text (which is a little redundant, I know), it
would look like this:
function foo() {
alert("Our function just ran!");
// This code won't run until we call the function 'foo()'
}

Compiled By: Ephrem Tesfaye Tsidu 18


Internet Programming I Chapter Four – JS Basics

We can then call that function and execute the code inside it anywhere in our script by writing the
following:
foo(); // Alerts "Our function just ran!"
We can call this function any number of times throughout our code. It saves a lot of time and
redundant coding.
Arguments
Having a function that executes the exact same code throughout your script isn’t likely to be all
that useful. We can “pass arguments” (provide data) to native and custom functions in order to
apply a function’s logic to different sets of data at different times.
To hold a place for the arguments, add one or more comma-separated variables in the parentheses
at the time the function is defined. Then, when we call that function, anything we include between
the parentheses will be passed into that variable as the function executes. This might sound a little
confusing, but it’s not so bad once you see it in action.
For example, let’s say we wanted to create a very simple function that alerts the number of items
contained in an array. We’ve already learned that we can use .length to get the number of items in
an array, so we just need a way to pass the array to be measured into our function. We do that by
supplying the array to be measured as an argument. In order to do that, we specify a variable name
in the parentheses when we define our custom function. That variable will then be available inside
of the function and will contain whatever argument we pass when we call the function.
function alertArraySize(arr) {
alert(arr.length);
}
Now any array we specify between the parentheses when we call the function will be passed to the
function with the variable name arr. All we need to do is get its length.
var test = [1,2,3,4,5];
alertArraySize(test); // Alerts "5"
Returning a value
This part is particularly wild, and incredibly useful. It’s pretty common to use a function to
calculate something and then give you a value that you can use elsewhere in your script. We could

Compiled By: Ephrem Tesfaye Tsidu 19


Internet Programming I Chapter Four – JS Basics

accomplish this using what we know now, through clever application of variables, but there’s a
much easier way.
The return keyword inside a function effectively turns that function into a variable with a dynamic
value! This one is a little easier to show than it is to tell, so bear with me while we consider this
example.
function addNumbers(a,b) {
return a + b;
}
We now have a function that accepts two arguments and adds them together. That wouldn’t be
much use if the result always lived inside that function, because we wouldn’t be able to use the
result anywhere else in our script.
Here we use the return keyword to pass the result out of the function. Now any reference you make
to that function gives you the result of the function—just like a variable would.
alert( addNumbers(2,5) ); // Alerts "7"
In a way, the addNumbers function is now a variable that contains a dynamic value: the value of
our calculation. If we didn’t return a value inside of our function, the preceding script would alert
“undefined”, just like a variable that we haven’t given a value.
The return keyword has one catch. As soon as JavaScript sees that it’s time to return a value, the
function ends. Consider the following:
function bar() {
return 3;
alert("We'll never see this alert.");
}
When you call this function using bar(), the alert on the second line never runs. The function ends
as soon as it sees it’s time to return a value.

Compiled By: Ephrem Tesfaye Tsidu 20


Internet Programming I Chapter Four – JS Basics

4.4 Flow control in JavaScript


In any programming language, the code needs to make decisions and carry out actions accordingly
depending on different inputs. We need decisions because the code we write can usually take more
than one direction depending on different situations. To determine which direction our code should
take, we need to have decision-making mechanism. These are the common steps we take while we
want to make any kind of decision.
 Evaluation: This is when you analyze values in your script to determine whether they
match expected results or not.
Example: If student scores 50 or more, it means score is a pass፣ If student scores
less than 50, it means score is a fail
var a = 82;
(a <= 50)
 Decision: Using the results of the evaluation, you will decide which path to take.
Example፡ The decision is to determine if student got a pass or fail score
var a = 32;
(a <= 55)
Decision: True
 Action: This is what you do after the decision is made.
Example: Passing or failing the student
console.log("RAISE YOUR HAND!");
console.log("You failed");
 Loops: On occasions where you must do the evaluation and decision steps repeatedly, you
use loops. Loops are used in JavaScript to perform repeated tasks based on a condition in
a more manageable and organized manner.
Example: Score of 100 students
Conditional Statements
if statements
Definition: An “if” statement is a programming conditional statement that we use to specify a
block

Compiled By: Ephrem Tesfaye Tsidu 21


Internet Programming I Chapter Four – JS Basics

Syntax: We start by using the key word "if", put the conditions within a bracket. Note that if is in
lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
if (condition) {
// write the code you want to be executed if the condition is true
}
Example:
var pass = 50;
var score = 17;
if (score >= pass) {
console.log("Hey you passed");
}
if (score <= pass) {
console.log("You failed");
}
The “else” statement
Definition: We use the “else” statement to specify a block of code to be executed when the
condition under the “if” statement is false.
Syntax:
if (condition) {
// write the code you want to be executed if the condition is true
} else {
// write the code you want to be executed if condition is false
}
Example:
var score = 82;
if (score >= pass) {
console.log("Hey you passed");
}else{
console.log("You failed");
}

Compiled By: Ephrem Tesfaye Tsidu 22


Internet Programming I Chapter Four – JS Basics

The “else … if” statement


Definition: There will be times where you want to test multiple conditions. That is where the else
if block comes in. When the “if” statement (the first statement) is false, the computer will move
onto the “else if” statement and executes it.
Syntax:
if (condition 1 is true) {
// code is executed
} else if (condition 2 is true) {
// code is executed
} else {
// code is executed
}
Example: Let’s instruct Chu’lo the computer
If (checkIfFolderExists('Abebe')) {
console.log("Folder already exists");
}else{
createFolder('Abebe');
}
Switch statements
Definition: instead of using this long if else statement, you might choose to go with an easier to
read switch statement. The switch statement starts with a variable called the switch value. Each
case in “switch statement” indicates the possible value and if there is a match when comparing the
input value with values of a case, the code associated with the match will run.
Syntax:
switch(expression) {
case x:
// the code you want to be executed if expression matches value of the case
break;
case y:
// the code you want to be executed if expression matches value of the case

Compiled By: Ephrem Tesfaye Tsidu 23


Internet Programming I Chapter Four – JS Basics

break;
default:
// the code you want to be executed if expression matches value of the case
}
How it works:
 The expression in a “switch statement” is evaluated only once with each case
 In a “switch statement”, the comparison is between the expression and the values under
each case
 If there is a match between the expression and the value of any of the cases, the code block
associated will be the one to be executed
 If multiple cases match a case value, the first case is selected.
 If there is no match while comparing the expression and the value of each case, the default
code will be executed
 When JavaScript reaches a break keyword, it breaks out of the switch block. This will stop
the execution inside the switch block. Note: It is not necessary to break the last case in a
switch block. The block breaks (ends) there anyway
 Default clause in switch statement works as the same as else clause in if else block. The
“default” keyword specifies the code to run if there is no match between the condition and
the expression.
 The default statement doesn't have to come at the end. It may appear anywhere in the body
of the switch statement.
 If no default label is found, the program continues to the statement(s) after the switch. If
default is not the last case in the switch block, remember to end the default case with a
break.
Example
var greetings;
var timeOfDay;
timeOfDay = "afternoon";

switch (timeOfDay) {

Compiled By: Ephrem Tesfaye Tsidu 24


Internet Programming I Chapter Four – JS Basics

case "morning":
greetings = "Good morning";
break;
case "afternoon":
greetings = "Good afternoon";
break;
case "evening":
greetings = "Good evening";
break;
default:
greetings = "Hi there";
break;
}
console.log(greetings);
Looping Statements
JavaScript For Loop
Defnition: For loops are commonly used to count a certain number of iterations to repeat a block
of code. Meaning, we use for loop when we want to execute the code for a SPECIFIED amount of
time
Syntax:
for (initialization; condition; post/final-expression) {
// statements (code block to be executed)
}
As you can see it from the syntax above, the JavaScript for loop statement allows you to create a
loop with three optional expressions that are separated by semicolon (;).
 The initialization expression: This expression is commonly used to create a counter
variable. A counter variable is a variable that keeps track of the number of times a specific
piece of code is executed. A counter variable basically counts the loop. All the variable
does is tell our loop where it should start counting from. This is like saying, “we are going

Compiled By: Ephrem Tesfaye Tsidu 25


Internet Programming I Chapter Four – JS Basics

to start counting starting from whatever value we give it in here”. We usually provide 0 as
value for the initial counter. However, it can be a different number too.
 The initialization expression is executed only once when the loop starts.
 If you use the var keyword to declare the counter variable, the variable will have
either function or global scope. In other words, you can reference the counter
variable after the loop ends. However, if you use the let keyword to declare the
counter variable, the variable will have a blocked scope, which is only accessible
inside the loop. See the example below:
for (let counter = 1; counter < 5; counter++) {
console.log(counter); // prints numbers 1 to 4
}
console.log(counter); prints “ReferenceError: counter is
not defined” because we used let to define counter
 Condition: This is the expression that is checked one time prior to every iteration. If the
condition evaluates to true; the loop’s statement is executed. If it evaluates to false, the
loop stops. The loop is terminated if the condition evaluates to false. See the example
below:
for (var counter = 1; counter < =10; counter++) {
console.log(counter);
}
In the above example, we want the code to be executed 10 times. What the condition
expression (counter < =10) does is check if we have already run the code 10 times. If we
haven't, it runs the code again
 If you want to stop the loop before the condition expression evaluates to false,
use break statement. In the example below, even if the condition evaluates true
when j is 8 or 9, the code will not run because we used break when j is 7. Thus,
the loop terminates when j reaches 7.
for (var j = 1; j <= 10; j++) {
if (j === 7) {
break;

Compiled By: Ephrem Tesfaye Tsidu 26


Internet Programming I Chapter Four – JS Basics

}
console.log(j); // prints numbers 1 to 6 and loop
stops
}
 The condition is optional. If you omit it, the for-loop statement considers it as true.
If you omit the condition expression, you need to use a break statement to terminate
the loop.
for (let counter = 1;; counter ++) {
console.log(j);
if (j >= 10) {
break;
}
}
 Post/final-expression: This expression is run after every single iteration. Generally, you
use the post-expression to update the counter variable (either to increment or decrement
the counter)
 When the initialization expression, condition expression and final
expression parts come together, the meaning they give to the following for
loop will be:
for (var i = 0; j <= 10; i++) {
console.log(i); // prints numbers 0 to 10
}
Start counting your loop starting from 0. To keep track of how many times the code inside the for
loop block is executed, save that value on a variable called i. To start with, lets assign 0 to our
variable i. Then compare that i with 10, and if i is less than or equal 10, run the code. In the first
loop, i is 0, which is less than 10. So, the code executes. Once the code finishes executing, increase
the value of i by 1. In the second loop, i is 1. 1 is still less than 10, so, execute the code again. Once
the code finishes executing, increase the value of i by 1. In the third loop, i is 2. 2 is still less than
10, so, execute the code again. Repeat this process until i becomes greater than 10.

Compiled By: Ephrem Tesfaye Tsidu 27


Internet Programming I Chapter Four – JS Basics

Example:
var someNumbers = [7, 58, 27];
var lengthOfArray = 3;
var loopNumber = 0;
var someMessage = "";
var i;
for (i = 0; i < 3; i++){
loopNumber = i + 1;
someMessage = "Loop " + loopNumber + ":" + someNumbers[i];
console.log(someMessage);
}
Javascript while loop
Defnition: The JavaScript while statement creates a loop that executes the code within the while
block as long as the test condition evaluates to true. After every single code execution, it comes
back and checks if the condition expression is still true. If the condition expression evaluates to
false, execution continues with the statement after the while loop.
Syntax:
while (expression) {
// statement (code block to be executed)
}
 The while loop evaluates the expression before each iteration, therefore, the
while loop is known as a pretest loop. For this reason, it is possible that the
statement inside the while loop is never executed.
Example:
var f = 0;
while (f < 3) {
console.log(f); // prints the numbers 0 to 2
f++;
}

Compiled By: Ephrem Tesfaye Tsidu 28


Internet Programming I Chapter Four – JS Basics

These are the steps involved in the above while loop example: First, outside of the loop, the f
variable is set to 0. Second, before the first iteration begins, the while statement checks if f is
less than 3 and executes the statements inside the loop body. Third, in each iteration, the loop
increments f by 1 and after 3 iterations, the condition f < 3 is no longer true, so, code executes 3
times the loop terminates.
Tip: A function that returns the sum of numbers between 1 and a given number
function addUp1(num) {
let sum = 0;
for (let i = 1; i <= num; i++) {
sum = sum + i;
}
return sum;
}
console.log(addUp1(600));// prints180300

Compiled By: Ephrem Tesfaye Tsidu 29


Internet Programming I Chapter Four – JS Basics

4.5 Event handler in JavaScript


The DOM
We know that JavaScript needs to access the HTML document and it also needs to know when the
user is interacting with the HTML. It is through DOM structure that JavaScript can access and
update the HTML document whenever a user interacts with the HTML.

For example, if you want a button on your website to change its color to green when a user clicks
on this button, you need to be able to select this specific button and write a logic that changes the
color of the selected element into green using JavaScript. DOM organizes our HTML document
in an object form so that JavaScript can manipulate (access and modify/update the any HTML
element). Therefore, DOM is the link between an HTML web page and JavaScript.

The DOM is a structure/standard/syntax that allow JavaScript to access, modify, and update the
structure of an HTML page. The DOM is a logical tree-like model/representation of our HTML.
DOM represents the HTML page using a series of objects. The main object is the document object,
which in turn houses other objects which also house their own objects, and so on.

 DOM is not part of HTML


 DOM is not part of JavaScript. However, JavaScript interacts with the created DOM object
 DOM is a language-agnostic structure. Meaning, DOM can interact with various languages
other than JavaScript

The DOM tree

A simple way to think of the DOM is in terms of the document. You saw documents diagrammed
in this way when you were learning about CSS selectors.

<html>
<head>
<title>Document title</title>
<meta charset="utf-8">
</head>
<body>

Compiled By: Ephrem Tesfaye Tsidu 30


Internet Programming I Chapter Four – JS Basics

<div>
<h2>Subhead</h2>

<p>Paragraph text with a <a href="foo.html">link</a>


here.</p>
</div>
<div>
<p>More text here.</p>
</div>
</body>
</html>

The DOM is a collection of nodes:

 Document node
 Element nodes
 Attribute nodes
 Text nodes

Compiled By: Ephrem Tesfaye Tsidu 31


Internet Programming I Chapter Four – JS Basics

Each element within the page is referred to as a node. If you think of the DOM as a tree, each node
is an individual branch that can contain further branches. But the DOM allows deeper access to
the content than CSS because it treats the actual content as a node as well. The next figure shows
the structure of the first p element. The element, its attributes, and its contents are all nodes in the
DOM’s node tree.

DOM Manipulation

Earlier we said that DOM represents the HTML page using a series of objects, the document object
being the main object. The document object in turn houses other objects which also house their
own objects, and so on.

So, when we say, “DOM manipulation”, it simply means changing the DOM (the HTML
document). This in turn means, changing the HTML elements that DOM converted into objects,
in response to a user’s action

Manipulating DOM involves two steps:

1. Finding/selecting the element we want to work with


2. Altering the text or attributes of that element

Compiled By: Ephrem Tesfaye Tsidu 32


Internet Programming I Chapter Four – JS Basics

The “document object” makes manipulation of the HTML document possible: The "document"
object in JavaScript is the door to the DOM structure. This is the name of the JavaScript object
that contains all the methods and properties to help us access and manipulate the DOM elements.
The "document object” allows us to access the root node of the DOM tree. You can access the
other child nodes of the DOM as properties of the “document object”.

Example, to access the body node: console.log (document.body);

1. Finding/selecting the element we want to work with

There are three common methods provided by the document object that we can use to select one
specific element. Let’s look at them below.

1. getElementById() method: The getElementById method accepts CSS’ id selector as its


argument and returns an element whose id matches the passed string/id. Since the ids of elements
are always unique to that element, this is a faster way to select an element. If the id is not found,
then this method returns null.

2. querySelector() method: The querySelector method takes CSS selectors as its argument and
returns the first element that matches the passed selector. Meaning, the method can take ids, classes
and tag names as its argument.

document.querySelector("#hi"); // selects the element with “hi” id name

document.querySelector(".bye"); // selects all elements with “hi” class name, but


returns first element in the document with class name

document.querySelector("div"); // selects all elements with “div” tag, but returns first
div

3. getElementsByClassName(): Just like getElementsByTagName(), this method also returns a


live HTMLCollection representing an array-like object of all elements with the specified class
name.

Syntax: document.getElementsByClassName(classname)

Compiled By: Ephrem Tesfaye Tsidu 33


Internet Programming I Chapter Four – JS Basics

getElementsByClassName(“red”)// retunds HTML collection with all elements having the “red”
class

Selecting one element from an HTMLCollection: See example code above

var el = document.getElementsByClassName("red");

console.log(el[1]); //selects the 2nd li element with red class

console.log(el.item(0));// selects the 1st li element with red class

4. getElementsByTagName() method: The method takes a tag name and returns a collection of
all elements in the document with the specified tag name, as an HTMLCollection object.

Syntax: document.getElementsByTagName(tagname)

getElementsByTagName("li")); //returns HTMLCollection with all <li>

Selecting one element from an HTMLCollection: See example code above

var el = document.getElementsByTagName("li");

console.log(el.item(0));// returns the 1st li element

console.log(el[1]); // returns the 2nd li element

5. Traversing between multiple elements: Traversing is the act of selecting an element from
another/neighboring element.

A. Traversing downwards:

 firstElementChild(): The firstElementChild property returns the first child element of


the specified element.

console.log(document.getElementById("listOfFruits").firstElementChild);//
prints the first li element under the ul

 lastElementChild(): The lastElementChild property returns the last child element of


the specified element.

Compiled By: Ephrem Tesfaye Tsidu 34


Internet Programming I Chapter Four – JS Basics

console.log(document.getElementById("fruitId").lastElementChi ld);// prints


the last li element under the ul

B. Traversing upwards:

 parentElement(): parentELement is a property that lets you select the parent element.
parentElement is great for selecting one level upwards

console.log(document.getElementById("one").parentElement);// prints the <ul>


which is the parent to all the <li>

C. Traversing sideways:

 previousElementSibling: The previousElementSibling property returns the previous


element of the specified element, in the same tree level. Look at the example above:

console.log(document.getElementById("three").previousElement
Sibling)//prints the 2nd li

 nextElementSibling: The nextElementSibling property returns the element


immediately following the specified element, in the same tree level. Look at the
example above:

console.log(document.getElementById("two").nextElementSibling); // prints
the 3rd li

2. Altering the text or attributes of that element

The HTML DOM allows JavaScript to change the content of HTML elements. Meaning, we can
add, update or remove the HTML tag, the text content in an HTML element, or the entire block of
HTML code from your page. These are the most common methods that allow us add, update or
remove contents in an HTML document.

Let’s use the below HTML document as an example to explain altering:

<div id="bigId">

<div>Hello</div>

Compiled By: Ephrem Tesfaye Tsidu 35


Internet Programming I Chapter Four – JS Basics

<ul id="listOfFruits">

<li id="one" class="red">Apple</li>

<li id="two" class="yellow">Mango</li>

</ul>

</div>

1. createElement() method: The createElement() method creates an Element Node with the
specified element name.

Syntax: document.createElement(nodename)

Note: After the element is created, use the element.appendChild() or


element.insertBefore() method to insert it to the HTML document

var liElem = document.createElement("li");

var parent = document.getElementById("listOfFruits");

parent.appendChild(liElem);

console.log(parent); // shows that a new <li> is added as the last child of the
parent node (the <ul>)

2. appendChild() method: The appendChild() method appends a set of node objects as the
last child of a node. See the above example.

Syntax: node.appendChild(node)

3. prepend () method: The method inserts a set of node objects before the first child of the
Element. See the above example.

Syntax: node. prepend(node)

Let’s insert an <li> as the first child of our <ul>

var liElem2 = document.createElement("li");

Compiled By: Ephrem Tesfaye Tsidu 36


Internet Programming I Chapter Four – JS Basics

var parent = document.getElementById("listOfFruits");

parent.prepend(liElem2);

console.log(parent);// shows that a new <li> is added as the first child of the
parent node (the <ul>)

4. textContent() method: The textContent property changes or returns the text content of the
specified node, and all its descendants. TextContent() returns all text contained by an
element and all its children.

Syntax: node.textContent

Let’s change the text content of our <div> that has "bigId" as its id

var content = document.getElementById("bigId");

console.log(content.textContent);// prints “hello”, “apple”, and “mango”

content. textContent = "New text here";

console.log(content.textContent);// prints "New text here"

5. removeChild() method: The removeChild() method removes a specified child node of the
specified element. Note: Use the appendChild() or insertBefore() methods if you want to
insert the removed node back into the same document.

Syntax; removeChild(child);

Let’s remove the <li> child from our <ul>

var ULcontainer = document.getElementById("listOfFruits");

var unwantedLi = document.getElementById("two");

console.log(ULcontainer); // prints <ul> with all its <li> children

ULcontainer.removeChild(unwantedLi); // prints <ul>, but the <li> with


"two" id is removed

Compiled By: Ephrem Tesfaye Tsidu 37


Internet Programming I Chapter Four – JS Basics

6. hasAttribute() method: The hasAttribute() method returns a Boolean value (true or false)
indicating whether the specified element has the specified attribute or not.

Syntax: element.hasAttribute(attributename)

<form id=" formID " >

<label >First Name</label>

<input type="text" name="firstName"

<label for="">Last Name</label>

<input type="text" name="lastName" >

</form>

Let’s check if our <form> element has “name” and “id” attributes

var myForm = document.getElementById("formID");

console.log(myForm.hasAttribute("name")); // prints false because the


<form> element doesn't have a name attribute

console.log(myForm.hasAttribute("id")); //prints true because <form>


element has id attribute.

7. getAttribute() method: The getAttribute() method returns the value of the attribute of an
element.

Syntax: element.getAttribute(attributename)

Let’s print the value of the “name” attribute for our first name <input>

var firstInputVal = document.getElementsByTagName("input")[0];

console.log(firstInputVal.getAttribute("name")); // returns "firstName"


which is the value of the "name" attribute for first name <input>

Compiled By: Ephrem Tesfaye Tsidu 38


Internet Programming I Chapter Four – JS Basics

8. setAttribute() method: The setAttribute() method adds the specified attribute to an


element and gives it the specified value. If the specified attribute already exists, only the
value is set/changed. Otherwise, a new attribute is added with the specified name and value.

Syntax: element.setAttribute(attributename, attributevalue)

 attributename parameter specifies the name of the attribute whose value is to be set.
Even if you put upper case for the name, the attribute name is automatically
converted to all lower-case when setAttribute() is called
 attributevalue parameter is the value to assign to the attribute

Let’s add a “value” attribute to our first name input. The value will be a placehoder for our
First Name input.

var firstInputVal = document.getElementsByTagName("input")[0];

firstInputVal.setAttribute(" value ", " first name ");// placeholder input value
of “first name” added to our <input>

9. removeAttribute() method: The removeAttribute() method removes the specified


attribute from an element.

Syntax: element.removeAttribute(attributename)

Let’s remove the “type” attribute form the first name <input>

var firstInputVal = document.getElementsByTagName("input")[0];

firstInputVal.removeAttribute("type");// removes the “type” attribute

console.log(firstInputVal.getAttribute("type")); // returns null because we


just removed the "type" attribute

10. Changing CSS Values with the DOM “style” property: We use the style property to
manipulate the inline style of the HTML elements using JavaScript. The style property is
used to get as well as add the inline style of an element using different CSS properties. We
can set almost all the styles for the elements like colors, fonts, text alignments, margin,
borders, background images, sizes, and more.

Compiled By: Ephrem Tesfaye Tsidu 39


Internet Programming I Chapter Four – JS Basics

The style property is extremely helpful to dynamically change the visual representation of
an HTML element using JavaScript. Note: the JavaScript syntax for setting CSS propertie
is slightly different than CSS (Ex: backgroundColor instead of background-color).
Syntax:
 To return style properties: = element.style.property
 To set/add style properties: = element.style.property = value

Example

Style background color property: The backgroundColor property sets or returns the
background color of an element.

Let’s change the background color of 2nd <li> into yellow and print the changed color

var secondLi = document.getElementById("one");

secondLi.style.backgroundColor = "yellow"; // changes the background color


of 2nd <li>to yellow

console.log(secondLi.style.backgroundColor); // prints "yellow"

Event Handling

Events in JavaScript are what happens on the browser when a user browses/manipulates a any
website. Change in the state of any object is known as event, i.e., event describes the change in the
state of the source. HTML/browser events are "changes" that happen to HTML elements when a
user or the browser manipulates the website. When the page loads, it is called an event. When the
user clicks a button, presses any key or closes/resizes a window, these too are events.

Your job as a JavaScript developer is to write a script that responds to an event that happens on
the browser. This is what makes websites interactive. When one interacts with a web page (like
clicking a button), that interaction is registered as an event on the browser. In response to that
event, the script that is bound with that event changes something on the web page. Event in
JavaScript are also called HTML or browser events. One key concept to understand in here is that
you, as a web developer, will be responsible to prepare the scripts in response to potential events
that could happen on your website.

Compiled By: Ephrem Tesfaye Tsidu 40


Internet Programming I Chapter Four – JS Basics

Event types

The browser triggers many events, and our JavaScript code reacts/gets executed in response to
these events. Below, please find some of the most common event types and event names:

 UI/Window events: These events occur as the result of any interaction with the browser
window rather than the HTML page. The various UI events are as follows. In these events,
we attach the event listener to the window object, not the document object
 Load event: The event fires when the browser finishes loading a page
 Unload event: This event fires when This event fires before the users leave the
page, probably because user requested a new page
 error event: This event fires when the browser encounters a JavaScript error or a
value that doesn’t exist
 resize event: This event occurs when a user changes/resizes the current size of the
browser window
 Scroll event: This event fires when the user scrolls up/down on the browser
window. It can relate to the entire page or a specific element on the page.
 Key board events: These events fire when a user interacts with a keyboard
 keydown event: This event fires when user first presses any key on the keyboard.
Note: If the user holds down the key, this event fires repeatedly.
 keyup event: This event fires when a user releases any key on the keyboard.
 keypress event: Just like keydown event, this event fires when a user presses any
key on the keyboard. However, the pressing of key results in printing a character
on the screen. The keypress event will not fire for enter, tab or arrow keys as
pressing them will not result in printing characters on the screen, but the keydown
event will fire if a user presses these keys.
 Note: The keydown and keypress events fire before a character appears on the
screen, the keyup fires after it shows.
 Mouse events: These events fire when the mouse moves, or the user clicks a button. All
the elements of the page support these events.
 Click event: This event fires when the user presses on and releases the primary
mouse button (usually the left button).

Compiled By: Ephrem Tesfaye Tsidu 41


Internet Programming I Chapter Four – JS Basics

Note 1: This event also fires if the user presses the “Enter” key on the keyboard
when an element has focus.

Note 2: For touchscreen devises, a tap on the screen acts like a single left-click

Note 3: We can add the above two events to any element, but it’s better to apply it
only on the items that are usually clicked (like button element)

 dbclick event: This event fires when user quickly presses and releases a button twice

Note 1: For touchscreen devises, a double-tap on the screen acts like a double
leftclick.

Note 2: We can add the above two events to any element, but it’s better to apply it
only on the items that are usually clicked (like button element)

 mouseover event: It fires when the user moves the cursor, which was outside an
element before, inside the element, in short, when a user moves the mouse over an
element.
 mouseout event: This event fires when the user moves the cursor, which was inside
an element before, outside the element, in short, when users move the mouse from
an element
 Form Events: These events are common while using forms on a webpage. We find the
submit event mostly in form of validation (Ex: if a user misses a required information or
enters an incorrect input, submit event fires to check the form values before the data is
sent/submitted to the server).
 change event: This event occurs when the value of an element has been changed.
Example, the change event fires when the checked value in check box, or radio
button changes
 submit event: This event fires when a user submits a form. The change occurs on
the <form> element when user submits a form using a button or a key.
 cut event: This event fires when a user cuts a content from any HTML element.

Note 1: The cut event is mostly used on <input> elements with type="text"

Compiled By: Ephrem Tesfaye Tsidu 42


Internet Programming I Chapter Four – JS Basics

Note 2: Although the cut event is supported by all HTML elements, it is not
possible to cut the content of a <p> element, unless we add the “contenteditable”
attribute and give it a value of "true".

 paste event: This event fires when a user pastes content in an element

Note 1: The paste event is mostly used on <input> elements with type="text"

Note 2: Although the paste event is supported by all HTML elements, it is not
possible to cut the content of a <p> element, unless we add the “contenteditable”
attribute and give it a value of "true".

 copy event: This event happens when a user copies the content of an element (ex:
copying content from a form field)

Tip: The copy event is mostly used on <input> elements with type="text".

 select event: This event fires when a user selects some text in an element.

Note: The onselect event is mostly used on <input type="text"> or <textarea>


elements.

 Focus and blur events: These events fire when the HTML elements you can interact with
gain/ lose focus. They are most commonly used in forms and especially helpful when you
want to do the following tasks: The tips are usually shown in the elements other than the
one the user is interacting with. To trigger form validation as a user moves from one control
to the next without waiting to submit the form.
Here are some of the focus and blur events:
 Focus/focusin event: This event fires, when an element gains focus.
 Blur/focusout event: This event fires, when an element loses focus

Event handlers/listeners

An event handler is also known as an event listener. An event handler/listener is a specific script
(JavaScript code) that gets executed when a particular event (such as clicking of a button) happens

Compiled By: Ephrem Tesfaye Tsidu 43


Internet Programming I Chapter Four – JS Basics

on an HTML element. An event handler is a script/function that listens to the event and responds
accordingly to the event.

When a user interacts with any HTML element on a web page, there are three steps involved in
triggering a script associated with an event:

1. Selecting an element: The element is selected to bind it with the event handler (JavaScript
function) when an event occurs on it

2. Binding an event: This is to identify the specific event that will trigger the event handler to
execute.

3. Attach a script: This is to instruct the web browser which specific event handler to execute
when a specific event happens

Note: The script that you want to bind with an event needs to be written first

Ways to bind an event

There are three ways to assign/bind event handlers to an event:

1. HTML event handler attributes/inline event handlers (as an attribute)

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. To
handle events using this method, all you need to do is to use an HTML attribute with the name of
the event handler function.

Example: Let’s try to change the color of our button’s text to red when the <button> is clicked

Our code in the JavaScript file:

function changeButtonColor() {

var myButton = document.getElementById("buttonId");

myButton.style.color = "red";

Attaching the event handler function to when there is a click event on our <button> element:

Compiled By: Ephrem Tesfaye Tsidu 44


Internet Programming I Chapter Four – JS Basics

<button id="buttonId" onclick="changeButtonColor()">Change Color</button>

This approach (using inline event handlers) is considered a bad practice for the following reasons:

 The event handler code is mixed with the HTML code, which will make the code more
difficult to maintain, especially on a larger scale it can get quite messy. Look at this
example: how unclean it will be to have all these event handlers in our <button>

<button onclick="changeButtonColor()" ondblclick="showClickedAlert()"


onfocus="changeBackgroundColor()" >Change Color</button>

 The approach won’t allow us bind more than one event handler for an event. Meaning, if
we use the inline event handling approach, we cannot assign a text color changer function
and a background color changer function for a single <button> click event.
2. Traditional/DOM Level 0 event handlers (as a method)

Each element has event handler properties (or onevent properties) such as onclick, ondblclick or
onfocus. Under this event handling approach, you just need to set/assign the event handler property
to a function (event handler function).

Syntax: element.onevent = functionName;

Notice that the event name is preceded by "on"

Steps involved under traditional DOM event handling:

 First, select the element you want to bind an event with


 Then bind the element with the event handler
 Finally attach the event handler function on the event (onevent property)

Example: Let’s try to change the text color of a <button> to red when a user clicks on the <button>

Method 1: It is fine to make the handler function a separate named function, like below:

 Selecting the <button> we want to bind the event (click) with

let myButton = document.getElementById("buttonId");

 Binding an event handler with the element selected using a named function

Compiled By: Ephrem Tesfaye Tsidu 45


Internet Programming I Chapter Four – JS Basics

var changeToRed = function () {

myButton.style.color = "red";

};

 Attaching the event handler function with the event handler property (onclick)

myButton.onclick = changeToRed

Method 2: We can use anonymous handler function like below

var myButton = document.getElementById("buttonId");

myButton.onclick = function () {

myButton.style.color = "red";

};

Under traditional DOM event handling, we can only attach a single function to an event.

3. DOM Level 2 event handlers (addEventListener)

Under this event handling approach, we will add/remove the event handler as a listener for an
element using the addEventListener() method. This is the most favored way of handling events as
the approach allows adding (removing) of multiple event handlers for a single event using the
event listener methods.

DOM Level 2 Event Handlers provide two main methods to register/deregister event listeners:

 addEventListener(): registers an event handler


 removeEventListener(): removes an event handler

Syntax: element.addEventListener(event, function)

element. removeEventListener(event, function)

addEventListene(): This is the recommended mechanism for adding event handlers in web pages.
Inside the addEventListener() function, we specify two parameters: the name of the event and
event handler function we want to run in response to the event.

Compiled By: Ephrem Tesfaye Tsidu 46


Internet Programming I Chapter Four – JS Basics

Example 1: Let’s change the text color of a <button> to red when <button> is clicked

var myButton = document.getElementById("buttonId");

myButton.addEventListener("click", function () {

myButton.style.color = "red";

});

Example 2: We can use a named function to do the same thing as example 1 above

var myButton = document.getElementById("buttonId");

let changeToRed = function () {

myButton.style.color = "red";

};

myButton.addEventListener("click", changeToRed);

removeEventListener (): The removeEventListener() removes an event listener that was added
via the addEventListener(). However, we need to pass the same parameters that were passed to the
addEventListener()

Exmaple 1: Let’s remove the above “addEventListener”.

var myButton = document.getElementById("buttonId");

let changeToRed = function () {

myButton.style.color = "red";

};

myButton.addEventListener("click", changeToRed);

myButton.removeEventListener("click", changeToRed);

Adding multiple listeners for a single event: Through DOM Level 2 event model, it is possible for
one event to trigger multiple event handler functions. Meaning, a specific object (ex:

Compiled By: Ephrem Tesfaye Tsidu 47


Internet Programming I Chapter Four – JS Basics

document.getElementById("elementId")), with a specific event ((ex: click or keypress) can be


assigned with any number of event-handler functions.

Let’s add different event handler functions and change the text color of button to red, change the
button’s background to yellow and alert a message that says, "button clicked!!!"

var myButton = document.getElementById("buttonId");

myButton.addEventListener("click", function () {

myButton.style.color = "red";

});

myButton.addEventListener("click", function () {

alert("button clicked!!!");

});

myButton.addEventListener("click", function () {

myButton.style.backgroundColor = "yellow";

});

Compiled By: Ephrem Tesfaye Tsidu 48


Internet Programming I Chapter Four – JS Basics

Reference Materials

 JS reserved keywords
https://www.w3schools.com/js/js_reserved.asp
 Operators Priority in JS
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Operators/Operator_Precede
nce
 JS Problems on algorithmic thinking
https://edabit.com/
 JS data types
https://cdn.ttgtmedia.com/rms/onlineimages/whatis-data_structure.png
 DOM tree
https://miro.medium.com/max/1040/1*YSA8lCfCVPn3d6GWAVokrA.png
 CSS using in JS
http://www.sitestepper.be/en/css-properties-to-javascript-properties-reference-list.htm
 JS Events
https://www.w3schools.com/tags/ref_eventattributes.asp

_______________The End!_______________

Compiled By: Ephrem Tesfaye Tsidu 49

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy