0% found this document useful (0 votes)
7 views92 pages

Notes (Scripting Language)

Uploaded by

giftmichty3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views92 pages

Notes (Scripting Language)

Uploaded by

giftmichty3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 92

Java Script

Table of Content
• Brief Introduction
• Embedding JavaScript in HTML
• Statements/Expressions
• Functions - Defining - Calling
• Event Handlers
Introduction
• JavaScript is Netscape’s cross-platform, object-
based scripting language for client and server
applications
• JavaScript is not Java. They are similar in some
ways but fundamentally different in others.
JavaScript and Java
• The JavaScript resembles Java but does not
have Java's static typing and strong type
checking.
• JavaScript supports most Java expression syntax
and basic control-flow constructs.
• JavaScript has a simple, instance-based object
model that still provides significant capabilities.
JavaScript Types
There’re 2 types:
* Navigator’s JavaScript, also called client-side
JavaScript
* LiveWire JavaScript, also called server-side
JavaScript
Why Study JavaScript?

• JavaScript is one of the 3 languages all web developers must learn:


• 1. HTML to define the content of web pages
• 2. CSS to specify the layout of web pages
• 3. JavaScript to program the behavior of web pages
Embedding JavaScript in HTML
• By using the SCRIPT tag
• By specifying a file of JavaScript code
• By specifying a JavaScript expression as the value for
an HTML attribute
• By using event handlers within certain other HTML
tags
SCRIPT Tag
The <SCRIPT> tag is an extension to HTML that can
enclose any number of JavaScript statements as
shown here:
<SCRIPT>
JavaScript statements...
</SCRIPT>
A document can have multiple SCRIPT tags, and
each can enclose any number of JavaScript
statements.
Hiding scripts in comment tags

<SCRIPT>
<!-- Begin to hide script contents from old browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>
Famous “Hello World” Program
<html>
<body>
<script language="JavaScript">
document.write(“Hello, World!”)
</script>
</body>
</html>
JavaScript code in a file
• The SRC attribute of the <SCRIPT> tag lets you
specify a file as the JavaScript source (rather
than embedding the JavaScript in the HTML).
• This attribute is especially useful for sharing
functions among many different pages.
Example
<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
………….
</SCRIPT>
</HEAD>
<BODY>
………….
Statements

•Conditional Statement: if…else


if (condition) {
statements1
} else {
statements2
}
Loop Statements
• for statement:
for ([initial-expression]; [condition];
[increment-expression]) {
statements
}
• while statement:
while (condition) {
statements
}
Expressions

•An expression is any valid set of literals,


variables, operators, and expressions that
evaluates to a single value; the value can be
a number, a string, or a logical value.
Expressions (cont’d)
• JavaScript has the following types of expressions:
* Arithmetic: evaluates to a number, for example
3.14159
* String: evaluates to a character string, for example,
"Fred" or "234"
* Logical: evaluates to true or false
Datatype conversion
• JavaScript is a loosely typed language. That means you
do not have to specify the data type of a variable when
you declare it, and data types are converted
automatically as needed during script execution. So, for
example, you could define a variable as follows: var
answer = 42
• And later, you could assign the same variable a string
value, for example, answer = "Thank you"
Datatype conversion (cont’d)
In expressions involving numeric and string values, JavaScript converts
the numeric values to strings. For example, consider the following
statements:
x = "The answer is " + 42
y = 42 + " is the answer."
Defining and calling Functions
• Functions are one of the fundamental building
blocks in JavaScript. A function is a JavaScript
procedure--a set of statements that performs a
specific task. A function definition has these
basic parts:
*The function keyword.
*A function name.
*A comma-separated list of arguments to the
function in parentheses.
*The statements in the function in curly braces.
Functions example
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function square(number) {
return number * number
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
document.write("The function returned ", square(5), ".")
</SCRIPT>
<P> All done.
</BODY>
Event handlers
JavaScript applications in the Navigator are
largely event-driven. Events are actions that
occur usually as a result of something the user
does. For example, clicking a button is an event,
as is changing a text field or moving the mouse
over a hyperlink. You can define event handlers,
such as onChange and onClick, to make your
script react to events.
Event Handler (cont’d)
Here’re a few event handler function
onAbort: user aborts the loading
onClick: user clicks on the link
onChange: user changes value of an element
onFocus: user gives input focus to window
onLoad: user loads page in Navigator
JavaScript Can Change HTML Content
• One of many JavaScript HTML methods is getElementById().
• The example below "finds" an HTML element (with id="demo"), and
changes the element content (innerHTML) to "Hello JavaScript":
• document.getElementById("demo").innerHTML = "Hello JavaScript";
• document.getElementById('demo').innerHTML = 'Hello JavaScript';
External JavaScript

• Scripts can also be placed in external files:


• External scripts are practical when the same code is used in many
different web pages.

• JavaScript files have the file extension .js.

• To use an external script, put the name of the script file in the src
(source) attribute of a <script> tag
External JavaScript Advantages

• Placing scripts in external files has some


advantages:
• It separates HTML and code
• It makes HTML and JavaScript easier to read and
maintain
• Cached JavaScript files can speed up page loads
• To add several script files to one page - use
several script tags
JavaScript Output

• JavaScript can "display" data in different ways:


• Writing into an HTML element, using innerHTML.
• Writing into the HTML output using document.write().
• Writing into an alert box, using window.alert().
• Writing into the browser console, using console.log().
Using innerHTML
• To access an HTML element, JavaScript can use the
document.getElementById(id) method.
• The id attribute defines the HTML element. The innerHTML property
defines the HTML content:
Using document.write()
• For testing purposes, it is convenient to use document.write():
• Using document.write() after an HTML document is loaded,
will delete all existing HTML
• The document.write() method should only be used for testing.
Using window.alert()
• You can use an alert box to display data:

You can skip the window keyword.


In JavaScript, the window object is the global scope object, that means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional
JavaScript Statements
• JavaScript statements are composed of:
• Values, Operators, Expressions, Keywords, and Comments.
• This statement tells the browser to write "Hello Dolly." inside an
HTML element with id="demo":
JavaScript Code Blocks
• JavaScript statements can be grouped together in code blocks, inside curly
brackets {...}.
• The purpose of code blocks is to define statements to be executed together.
• One place you will find statements grouped together in blocks, is in JavaScript
functions:
JavaScript Variables
• JavaScript variables are containers for storing data values.
• In this example, x, y, and z, are variables, declared with the var
keyword:
Using let and const (ES6)

• Before 2015, using the var keyword was the only way to declare a
JavaScript variable.

• The 2015 version of JavaScript (ES6) allows the use of the const
keyword to define a variable that cannot be reassigned, and the let
keyword to define a variable with restricted scope.

• Because it is a little complicated to describe the difference between


these keywords, and because they are not supported in older
browsers, the first part of this tutorial will most often use var.
JavaScript Identifiers
• All JavaScript variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
• The general rules for constructing names for variables (unique
identifiers) are:
• Names can contain letters, digits, underscores, and dollar signs.
• Names must begin with a letter
• Names can also begin with $ and _ (but we will not use it in this
tutorial)
• Names are case sensitive (y and Y are different variables)
• Reserved words (like JavaScript keywords) cannot be used as names
JavaScript Block Scope
Comparison and Logical Operators

• Comparison and Logical operators are used to test for true or false.
• Comparison operators are used in logical statements to determine
equality or difference between variables or values.
• Given that x = 5, the table below explains the comparison operators
Switch Statement

• The switch statement is used to perform different actions based on


different conditions.
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• If there is no match, the default code block is executed.
Example
• The getDay() method returns the weekday as a number between 0
and 6.

• (Sunday=0, Monday=1, Tuesday=2 ..)

• This example uses the weekday number to calculate the weekday


name:
Loops

• Loops can execute a block of code a number of times.


The For Loop
Break and Continue
• The break statement "jumps out" of a loop.
• The continue statement "jumps over" one iteration in the loop.
Arrays

• JavaScript arrays are used to store multiple values in a single variable.


• An array is a special variable, which can hold more than one value at a
time.
Access the Full Array
• With JavaScript, the full array can be accessed by referring to the
array name:
JavaScript Functions
• A JavaScript function is a block of code designed to perform a particular task.
• A JavaScript function is executed when "something" invokes it (calls it).
• A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().

• Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).

• The parentheses may include parameter names separated by commas:


• (parameter1, parameter2, ...)

• The code to be executed, by the function, is placed inside curly brackets: {}


Why Functions?
• You can reuse code: Define the code once, and use it many times.
• You can use the same code many times with different arguments, to
produce different results.

The ( ) Operator Invokes the Function


Function Invocation

• The code inside the function will execute when


"something" invokes (calls) the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Function Return
• When JavaScript reaches a return statement, the function will stop
executing.
• If the function was invoked from a statement, JavaScript will "return"
to execute the code after the invoking statement.
• Functions often compute a return value. The return value is
"returned" back to the "caller"
Functions Used as Variable Values
• Functions can be used the same way as you use variables, in all types
of formulas, assignments, and calculations.
Objects
• In JavaScript, almost "everything" is an object.
• Booleans can be objects (if defined with the new keyword)
• Numbers can be objects (if defined with the new keyword)
• Strings can be objects (if defined with the new keyword)
• Dates are always objects
• Maths are always objects
• Regular expressions are always objects
• Arrays are always objects
• Functions are always objects
• Objects are always objects
• All JavaScript values, except primitives, are objects.
Object Definition

• You define (and create) a JavaScript object with an object literal:


• var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
• Spaces and line breaks are not important. An object definition can
span multiple lines:
Classes

• ECMAScript 2015, also known as ES6, introduced JavaScript Classes.


• JavaScript Classes are templates for JavaScript Objects.
• Use the keyword class to create a class.
• Always add a method named constructor():
Class Inheritance
• To create a class inheritance, use the extends keyword.
• A class created with a class inheritance inherits all the methods from
another class
• The super() method refers to the parent class.
• By calling the super() method in the constructor method, we call the
parent's constructor method and gets access to the parent's
properties and methods.
• Inheritance is useful for code reusability: reuse properties and
methods of an existing class when you create a new class.
The HTML DOM (Document Object Model)
• When a web page is loaded, the browser creates
a Document Object Model of the page.
• The HTML DOM model is constructed as a tree of Objects:
HTML DOM
• With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
HTML DOM
• The HTML DOM is a standard object model and programming
interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
• In other words: The HTML DOM is a standard for how to get, change,
add, or delete HTML elements.
HTML DOM Methods

• HTML DOM methods are actions you can perform (on HTML
Elements).
• HTML DOM properties are values (of HTML Elements) that you can
set or change.
The DOM Programming Interface

• The HTML DOM can be accessed with JavaScript (and with other
programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each
object.
• A property is a value that you can get or set (like changing the
content of an HTML element).
• A method is an action you can do (like add or deleting an HTML
element).
• In the example above, getElementById is a method, while innerHTML
is a property.
• The most common way to access an HTML element is to use the id of
the element.
• In the example above the getElementById method used id="demo" to
find the element.
• The innerHTML property can be used to get or change any HTML
element, including <html> and <body>.
HTML DOM Document

• The HTML DOM document object is the owner of all other objects in
your web page.
• The document object represents your web page.
• If you want to access any element in an HTML page, you always start
with accessing the document object.
• Below are some examples of how you can use the document object to
access and manipulate HTML.
HTML DOM Elements
• Often, with JavaScript, you want to manipulate HTML elements.
• To do so, you have to find the elements first. There are several ways
to do this:
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections
HTML Element by Id
• The easiest way to find an HTML element in the DOM, is by using the
element id.
• This example finds the element with id="intro":
HTML Elements by Tag Name
HTML DOM - Changing CSS
• To change the style of an HTML element, use this syntax:
• document.getElementById(id).style.property = new style

You might also like