S - S 3 J S: ELF Tudy AVA Cript

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Semester 1, 2020

SELF-STUDY 3 JAVASCRIPT
The learning activities in this self-study (a.k.a PRIOR to Tutorial) are designed to consolidate and extend your
understanding of the topics covered in lectures in week 3.

You should complete all activities and questions until the tutorial in week 4.

JAVASCRIPT
JavaScript is the programming language of HTML and the Web, which allow you to make interactive web page.
JavaScript can change HTML content, HTML attribute values, HTML styles or can hide/show HTML elements.

The programs in this language called scripts which can be written right in a web page’s HTML and run
automatically as the page loads. Scripts are provided and executed as plain text; therefore, they do not need
special preparation or compilation to run.

Today, JavaScript can execute both in the browser and on the server. Any device that has a special program
called the JavaScript engine can run JavaScript. The browser has an embedded engine called as “JavaScript virtual
Machine”.

WHY TO LEARN JAVASCRIPT


JavaScript is most popular programming language. Once you know JavaScript, it helps you developing not only
front-end but also back-end software using different JavaScript based frameworks such as jQuery, Node.JS,
Angular, React and so on.

JavaScript is installed on every modern web browser. You do not need any special environment setup to learn
and build web page using JavaScript. For example, every browser (Firefox, Chrome and Safari) supports
JavaScript.

Apart from web development, JavaScript usage has now extended to mobile app development, desktop app
development, and game development. There are many opportunities for JavaScript programmer today.

CLIENT-SIDE JAVASCRIPT
Client-side JavaScript is the most common form of the language. It means that JavaScript code is executed on
the client-side. For example, when the user submits the form, the input is validated in the client-side and only if
the entries are valid, they would be submitted to the Web Server.

There are some advantages of using client-side JavaScript:

1. Less server interaction: It is able to validate user input before sending the page off to the server. It saves
server traffic, which means less load on your server.
2. Immediate feedback to the visitors: Users do not need to wait for a page reload to see if they have
forgotten to enter something.
3. Increased interactivity: It is able to create interfaces that react when the user hovers over them with a
mouse.

DEVELOPER CONSOLE
To see errors and get a lot of other useful information about scripts, “developer tools” have been embedded in
browsers.
Semester 1, 2020

GOOGLE CHROME/FIREFOX/EDGE AND OTHERS


Press F12 or, if you’re on Mac, then Cmd+Opt+J. The developer tools will open on the console tap by default. It
looks somewhat like this:

SAFARI
You need to enable the “Develop menu” first. Open Preferences and go to the “Advanced” pane. There’s a
checkbox at the bottom. Now Cmd+Opt+C can toggle the console.

JAVASCRIPT IN HTML FILE


All JavaScript code must appear the beginning <script> and ending </script>tags in HTML.

Our usual ‘Hello World!’ in JavaScript.


Semester 1, 2020

The JavaScript code is placed in the header section of the HTML file. You can place the JavaScript code in the
body section, but because the browser executes JavaScript code as it encounters that code, from top to bottom,
it is recommended to include your script at the very top of an HTML file so that the JavaScript code can be
executed as soon as Web page is loaded.

JAVASCRIPT IN A SEPARATE FILE


The JavaScript code is saved in the file ‘javaScript.js’. In this case, no ‘script tag’ is used here.

JavaScript.html

JavaScript.js

FIGURE 1. OUTPUT OF JAVASCRIPT.HTML

Placing scripts in external files has some advantages: it separates HTML and code; therefore, it makes HTML and
JavaScript easier to read and maintain and can speed up page loads.

JAVASCRIPT OUTPUT
Semester 1, 2020

JavaScript can display data in different ways:

Code Description
innerHTML Writing into an HTML element
document.write() Writing into the HTML output
window.alert() Writing into an alert box
console.log() Writing into the browser console

USING INNERHTML

USING DOCUMENT.WRITE()
Semester 1, 2020

USING WINDOW.ALERT

USING CONSOLE.LOG
Semester 1, 2020

JAVASCRIPT SYNTAX
Comments Human readable descriptions. You can add comments to your script to
make it easier to understand and maintain.
Variables Named placeholders that represent the bits of data
Operators It includes the commas, periods and other symbols that you use to
compare and assign values to variables
Functions Named groups of statements that you define once, and then reuse to
your content
Conditionals Logical constructions that you add to the script to decide whether the
particular condition is true or false eg) if-else
Loops Specialised forms of conditions. It checks a particular condition multiple
times until the condition becomes true or false. eg) for, while

COMMENTS
Comments can be used to make the code more readable.

Single Line comments Start with //


Multi-line comments Start with /* and end with */

DATATYPES
JavaScript has five primitive datatypes

1. Numbers: represents both integer and floating point numbers


Semester 1, 2020

2. Strings: must be surrounded by quotes

3. Boolean (logical type): it has only two values – true and false

4. Null: does not belong to any of the types described above.

5. Undefined: means “value is not assigned”


Semester 1, 2020

JavaScript variables can hold many data types: number, strings, objects and more:
https://www.w3schools.com/js/js_datatypes.asp

VARIABLES
Variables are containers for storing data values. You use the var Keyword.

var animal = “cat” ;

data
Variable Name
(unique identifier) Assigning value

The general rules for constructing names for variables:

- Names can contain letter, digits, underscores, and dollar signs


- Must begin with a letter
- Can begin with $ and _
- Case sensitive
- Reserved words cannot be used as names
Semester 1, 2020

Now, we are going to have quick JavaScript exercise. In this exercise, we are going to cover variables and
strings as well as the prompt and document.write() and console.log().

When you open the html file, it will ask for the user’s first name, last name and age. Then it will print out the
user’s full name in a sentence on the browser and print out the user’s age in a sentence on console.

FIGURE 2. JS_EXERCISE1.HTML

FIGURE 3. SCRIPT.JS

Output of document.write() Output of console.log()

FIGURE 4. FINAL OUTPUT OF JS_EXERCISE1.HTML

OPERATORS
Type Operator Description
Arithmetic operators + Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
Comparison operators == Equal to
=== Equal value and type
!= Not equal
!== Not equal value or type
> Greater than
Semester 1, 2020

< Less than


>= Greater than or equal to
<= Less than or equal to
Logical operators && And
|| Or
! Not

FUNCTIONS
A JavaScript function is a name of group of JavaScript statements that you can declare once at the top of your
script and call over and over again. That is, functions let use wrap bits of code up into REUSABLE packages.

Function declaration:

function name([parameter], [parameter], ..){


statements
return value
}

<Example>

Suppose you want to write code to sing “Twinkle Twinkle Little star”. All you need to do is write a function to
help you out as below.
Semester 1, 2020

To sing the song, you just need to call twinkle();

For more details: https://www.w3schools.com/js/js_functions.asp

CONDITIONS
IF - ELSE
The if-else conditional expression is used to test condition:

- If condition is true, all the statements that follow the if clause are executed
- If condition is false, all the statements that follow the else clause are executed

IF - ELSEIF
Semester 1, 2020

SWITCH
It is easier to check an expression for a bunch of different values without resorting a string of if-else statements

L OOPS
You can use to reiterate a series of statements over and over again with Loops

for

Printing numbers from 1 to 5 with a for loop.


Semester 1, 2020

While

Printing numbers from 1 to 5 with a While loop.

DOM MANIPULATION
The HTML DOM is a standard object model and programming interface for HTML. With the object model,
JavaScript can create dynamic HTML such as change all the HTML elements, attributes or CSS style in the page,
or remove/add HTML elements and attributes.

THE PROCESS
SELET an element and then MANIPULATE it

For example, we’ll change the <h1> color using JS.

FIGURE 5. EXMPLALE.HTML BEFORE ADDING JAVASCRIPT

1. We select “h1” and change color to “red”


Semester 1, 2020

2. We select “body” then manipulate the background using function with if-else statement as below. If
the background color of body is not white, the color is changed to ‘#3498db’

Apart from changing the style of HTML, you also can delete or add some text in HTML.
Semester 1, 2020

Explore more about DOM manipulation with JavaScript following the below link:

https://www.w3schools.com/js/js_htmldom_elements.asp

https://www.w3schools.com/js/js_htmldom_html.asp

https://www.w3schools.com/js/js_htmldom_css.asp

EVENT HANDLING
One of the main usages of JavaScript is ‘event handling’. Using JavaScript, we can perform certain actions at the
occurrence of the events such as mouse click, mouse over, dragging and dropping or pressing the enter key.

THE PROCESS
We SELECT and element and then add an EVENT LISTNER

For example, listen for a click on this <button> or listen for a hover event on the <h1>

THE SYNTAX
Too add listener, we use a method called addEventListner()

Let’s display a message when a button is clicked.

Following is a web page before we click the button.


Semester 1, 2020

After clicking the button is as below

Let’s look at another common one – mouse over and out

When you open the html file at first:

When you move mouse over to the paragraph:


Semester 1, 2020

When you move mouse out from the paragraph:

We just cover a basic of event handling. There are over 300 different events. Please explore more by following
the below links:

https://www.w3schools.com/js/js_htmldom_events.asp

https://www.w3schools.com/js/js_htmldom_eventlistener.asp
Semester 1, 2020

ACTIVITIES
GUESS THE OUTPUT OF THE CODE
Look at the below code. What does the following code return?

You might also like