Java PDF
Java PDF
JAVASCRIPT
Haider M. Habeeb
REFERENCES
• Jon Duckett. 2014. JavaScript and JQuery: Interactive Front-End Web
Development (1st ed.). Indianapolis, Indiana: John Wiley & Sons
Publishing
• Refsnes, H. and Refsnes, S. and Refsnes, K.J. and Refsnes, J.E. and
Henthorne, K.D. 2010. Learn JavaScript and Ajax with w3Schools.
Indianapolis, Indiana: Wiley Publishing
1
2/25/2018
COURSE OBJECTIVES
• How JavaScript can be used in browsers to make websites
more:
• interactive,
• interesting,
• and user-friendly.
• How can be made writing JavaScript a lot easier by using
jQuery.
REQUIREMENTS
• You will need to know how to build web pages using HTML
and CSS.
• No prior experience with programming is necessary.
• The only equipment you need to use this book are a
computer with a modern web browser installed, and your
favorite code editor, (e.g., Notepad, TextEdit. Sublime Text.
or Coda).
2
2/25/2018
WHAT ELSE
2. Learning the language itself, and, like all languages, you need to
know its vocabulary and how to structure your sentences.
JAVASCRIPT
3
2/25/2018
ACCESS CONTENT
• You can use JavaScript to select any element, attribute, or
text from an HTML page.
• For example:
• Select the text inside all of the <hl> elements on a page.
• Select any elements that have a class attribute with a
value of note.
• Find out what was entered into a text input whose id
attribute has a value of email.
4
2/25/2018
MODIFY CONTENT
• You can use JavaScript to add elements, attributes, and
text to the page, or remove them.
• For example:
• Add a paragraph of text after the first <hl> element.
• Change the value of class attributes to trigger new CSS
rules for those elements.
• Change the size or position of an <img> element.
PROGRAM RULES
• You can specify a set of steps for the browser to follow (like a recipe),
which allows it to access or change the content of a page.
• For example:
• A gallery script could check which image a user clicked on and
display a larger version of that image.
• A mortgage calculator could collect values from a form, perform a
calculation, and display repayments.
• An animation could check the dimensions of the browser window
and move an image to the bottom of the viewable area (also
known as the viewport).
5
2/25/2018
REACT TO EVENTS
• You can specify that a script should run when a specific event has
occurred. For example, it could be run when:
• A button is pressed
• A link is clicked (or tapped) on
• A cursor hovers over an element
• Information is added to a form
• An interval of time has passed
• A web page has finished loading
A QUICK REFRESHER
• HTML Element:
• An element consist of the opening and closing tags.
• There are a few empty elements with no content.
• Opening tags can carry attributes.
• Attributes have a name and value.
• The value is usually given in quotes.
6
2/25/2018
A QUICK REFRESHER
• CSS Rules:
• CSS uses rules to indicate how the content of elements should be displayed
in the browser.
• Each rule has a selector and declaration block.
• Each declaration has a property and a value.
7
2/25/2018
A
• What is a script and how do I create one?
• A script is a series of instructions that a computer can follow to
achieve a goal.
• You could compare scripts to any of the following:
• RECIPES
• HANDBOOKS
• MANUALS
WRITING A SCRIPT
8
2/25/2018
SOLVE PROBLEM
9
2/25/2018
• Syntax: How you put those words together to create instructions computers
can follow.
EXAMPLE
• Calculates the cost of a name plaque.
10
2/25/2018
EXAMPLE
• Tasks that have to be performed in order to
achieve the goals:
1. The script is triggered when the button is
clicked.
2. It collects the name entered into the
form field.
3. It checks that the user has entered a
value.
4. If the user has not entered anything, a
message will appear telling them to
enter a name.
5. If a name has been entered, calculate
the cost of the sign by multiplying the
number of letters by the cost per letter.
6. Show how much the plaque costs.
SUMMARY
11
2/25/2018
B
• How do computers fit in with the world around them?
MODEL
12
2/25/2018
MODEL
• A computer has no predefined concept of what a hotel or car is. It does not
know what they are used for. Your laptop or phone will not have a favorite
brand of car, nor will it know what star rating your hotel is.
• So how do we use computers to create hotel booking apps, or video games
where players can race a car?
• The answer: is that programmers create a very different kind of model,
especially for computers.
• Programmers make these models using data.
• the data is all the computer needs in order to follow the instructions you give
it to carry out its tasks.
13
2/25/2018
14
2/25/2018
NAME/VALUE PAIRS
• The idea of name/value pairs is used in both HTML and CSS.
• In HTML:
• an attribute is like a property; different attributes have different names, and
each attribute can have a value.
• in CSS:
• you can change the color of a heading by creating a rule that gives the
color property a specific value.
• Name/value pairs are used a lot in programming.
15
2/25/2018
EXAMPLE
• HOTEL OBJECT
• The hotel object uses property
names and values to tell you
about this particular hotel’
• CAR OBJECTS
• The car objects both share the
same properties, but each one
has different values for those
properties.
EVENTS
• In the real world, people interact with objects. These interactions can
change the values of the properties in these objects.
• Example: The car has been designed to respond differently when the driver
interacts with each of the two different pedals:
• The accelerator makes the car go faster
• The brake slows it down
16
2/25/2018
EVENT MODEL
Listen React
EVENT MODEL
• WHAT DOES AN EVENT DO?
• Programmers choose which events they respond to.
• When a specific event happens, that event can be used to trigger a specific
section of the code.
• Scripts often use different events to trigger different types of functionality.
• So a script will state which events the programmer wants to respond to, and
what part of the script should be run when each of those events occur.
17
2/25/2018
EVENT MODEL
EVENT
• HOTEL OBJECT
• A hotel will regularly have
bookings for rooms.
• Each time a room is reserved,
an event called book can be
used to trigger code that will
increase the value of the
bookings property.
• Likewise, a cancel event can
trigger code that decreases
the value of the bookings
property.
18
2/25/2018
METHODS
• WHAT IS A METHOD?
• Method typically represents how people (or other things) interact with an
object in the real world.
METHODS
• The code for a method can contain lots of instructions that together
represent one task.
• When you use a method, you do not always need to know how it achieves
its task; you just need to know how to ask the question and how to interpret
any answers it gives you.
19
2/25/2018
METHODS
• HOTEL OBJECT
• Hotels will commonly be asked if
any rooms are free.
• To answer this question, a
method can be written that
subtracts the number of
bookings from the total number
of rooms.
• Methods can also be used to
increase and decrease the
value of the bookings property
when rooms are booked or
cancelled.
METHODS
• CAR OBJECTS
• The value of the currentSpeed
property needs to go up and down
as the driver accelerates and
brakes.
• The code to increase or decrease
the value of the currentSpeed
property could be written in a
method, and that method could be
called changeSpeed ().
20
2/25/2018
• The events, methods, and properties of an object all relate to each other:
• Events can trigger methods, and methods can retrieve or update an object's
properties.
21
2/25/2018
22
2/25/2018
DOCUMENT
OBJECT
DOCUMENT OBJECT
• DOCUMENT OBJECT
• The current web page loaded into each window is modelled using a
document object.
• The title property of the document object tells you what is between the
opening <title> and closing </title> tag for that web page, and
• The Last Modified property of the document object tells you the date this
page was last updated.
23
2/25/2018
DOCUMENT OBJECT
• Using the document object, you can access and change what content
users see on the page and respond to how they interact with it.
• Like other objects that represent real-world things, the document object has:
• Properties
• Methods
• Events
DOCUMENT OBJECT
• PROPERTIES
• Properties describe characteristics of the current web page (such as the title of
the page).
• METHODS
• Methods perform tasks associated with the document currently loaded in the
browser (such as getting information from a specified element or adding new
content).
• EVENTS
• A user clicking or tapping on an element.
24
2/25/2018
DOCUMENT OBJECT
• The document object is just one of a set of objects that all major browsers
support.
• When the browser creates a model of a web page, it not only creates a
document object, but it also creates a new object for each element on the
page.
• Together these objects are described in the Document Object Model (DOM).
DOCUMENT OBJECT
25
2/25/2018
26
2/25/2018
27
2/25/2018
SUMMARY
C
• How do I write a script for a Web page?
• First, you need to know how JS will fit together with the HTML and CSS
in your web pages.
28
2/25/2018
<HTML>
• CONTENT LAYER
• . html files
{CSS}
• PRESENTATION LAYER
• .css files
• The CSS enhances the HTML page with rules that
state how the HTML content is presented
(backgrounds, borders, box dimensions, colors,
fonts, etc.).
29
2/25/2018
JAVASCRIPT()
• BEHAVIOR LAYER
• .js files
• This is where we can change how the page
behaves, adding interactivity. We will aim to
keep as much of our JavaScript as possible in
separate files.
PROGRESSIVE ENHANCEMENT
• These three layers form the basis of a popular approach to building web
pages called progressive enhancement.
30
2/25/2018
CREATING A BASIC
JAVASCRIPT
• This example adds a greeting into
an HTML page. The greeting
changes depending on the time of
day.
LINKING HTML TO JS
• When you want to use
JavaScript with a web page,
you use the HTML <script>
element to tell the browser it
is coming across a script.
• Its src attribute tells people
where the JavaScript file is
stored.
31
2/25/2018
RESULT
• After applying CSS rules
• Please note: Internet Explorer
sometimes prevents
JavaScript running when you
open a page stored on your
hard drive. If this affects you,
please try Chrome, Firefox,
Opera, or Safari instead.
32
2/25/2018
RUNNING JAVASCRIPT
• JavaScript
runs where it
is found in
the HTML.
SUMMARY
• The HTML <script> element is used in HTML pages to tell the browser to load the
JavaScript file (rather like the <link> element can be used to load a CSS file).
• If you view the source code of the page in the browser, the JavaScript will not
have changed the HTML, because the script works with the model of the web
page that the browser has created.
33
2/25/2018
34
3/6/2018
JAVASCRIPT
Haider M. Habeeb
JAVASCRIPT
1
3/6/2018
OBJECTIVES
• You will also learn how to give a web browser instructions you want it to
follow.
STATEMENTS
• A script is a series of instructions that a computer can follow one-by-one.
• Each individual instruction or step is known as a statement.
• Statements should end with a semicolon.
• Examples:
var today= new Date();
greeting = 'Welcome';
document.write(greeting) ;
• Some statements are surrounded by curly braces;
• these are known as code blocks.
• The closing curly brace is not followed by a semicolon.
2
3/6/2018
COMMENTS
• You should write comments to explain what your code does.
• They help make your code easier to read and understand.
• This can help you and others who read your code.
• SINGLE-LINE COMMENTS
var today = new Date(); // Create a new date object
var hour Now = today.getHours(); II Find the current hour
• MULTI-LINE COMMENTS
I* This script displays a greeting to the user based upon the current time.
It is an example from JavaScript & jQuery book *I
VARIABLES
• WHAT IS A VARIABLE?
• A script will have to temporarily store the bits of information it needs to do its job.
It can store this data in variables.
3
3/6/2018
VARIABLES
• How to assign variable a value?
DATA TYPES
• Numeric data type
• String data type
• Boolean data type
4
3/6/2018
VARIABLES
• Using a variable to
store a string.
VARIABLES
5
3/6/2018
VARIABLES
• Using a variable
to store a
boolean
VARIABLES
• Shorthand for creating variables
6
3/6/2018
VARIABLES
• The name must begin with a letter, dollar sign ($),or an underscore (_). It must
not start with a number.
• The name can contain letters, numbers, dollar sign ($), or an underscore (_).
Note that you must not use a dash(-) or a period (.) in a variable name.
VARIABLES
• All variables are case sensitive, so score and Score would be different
variable names, but it is bad practice to create two variables that have the
same name using different cases.
• Use a name that describes the kind of information that the variable stores.
• If your variable name is made up of more than one word, use a capital letter
for the first letter of every word after the first word. (Camel Case)
7
3/6/2018
ARRAYS
• An array is a special type of variable. It doesn't just store one value; it stores a
list of values.
EXPRESSIONS
• An expression evaluates into (results in) a single value. Broadly speaking
there are two types of expressions.
• Expressions that just assign a value to a variable
8
3/6/2018
OPERATORS
• Expressions rely on things called operators; they allow programmers to create
a single value from one or more values.
• Assignment Operators
• Arithmetic Operators
• String Operators
• Comparison Operators
• Logical Operators
SUMMARY
• A script is made up of a series of statements. Each statement is like a step in a
recipe.
• Scripts contain very precise instructions. For example, you might specify that a value
must be remembered before creating a calculation using that value.
• Variables are used to temporarily store pieces of information used in the script.
• Arrays are special types of variables that store more than one piece of related
information.
• JavaScript distinguishes between numbers (0-9), strings (text), and Boolean values
(true or false).
• Expressions evaluate into a single value.
• Expressions rely on operators to calculate a value.
9
3/6/2018
10
''
JAVASCRIPT
Haider M. Habeeb
JAVASCRIPT
1
''
2
''
FUNCTION
• What is a function? • Calling a function
FUNCTION
• Decelerating function that needs information
3
''
FUNCTION
• Getting a single value out of a function
FUNCTION
• Getting multiple values out of a function
4
''
ANONYMOUS FUNCTIONS
& FUNCTION EXPRESSIONS
• Function Declaration • Function Expression
Anonymous Function
IIFE
• Immediately Invoked Function
Expressions (IIFE)
• The final parentheses (shown on
green) tell the interpreter to call
the function immediately.
• The grouping operators (shown
on pink) are parentheses there to
ensure the interpreter treats this
as an expression.
5
''
IIFE
• To prevent conflicts between two scripts that might use the same variable
names.
VARIABLE SCOPE
• Local Variables
• Global Variables
6
''
OBJECT
• What is an object?
• Objects group
together a set of
variables and
functions to create a
model of a
something you
would recognize
from the real world.
OBJECT
7
''
OBJECT
• var person = "John";
• var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
• Key/value pair
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
8
''
OBJECT
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {
return this.firstName + “ “ + this.lastName;
}
OBJECT
• Object Definition
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue“
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
9
''
OBJECT
• Hotel Object:
• Key/value pairs
OBJECT
• Hotel object contains the following
key/value pairs:
• Variables have a name and can
assign them a value of a string,
number, or Boolean.
• Arrays have a name and a group of
values. (Each item in an array is a
name/value pair because it has an
index number and a value.)
• Named functions have a name and
value that is a set of statements to run
if the function is called.
• Objects consist of a set of name/value
pairs (but the names are referred to as
keys).
10
''
11
''
JAVASCRIPT
Haider M. Habeeb
JAVASCRIPT
1
''
OBJECT
OBJECT
• Literal Notation
2
''
OBJECT
• Accessing an Object:
• You can access the properties and methods of an object using dot notation
OBJECT
• Accessing an Object:
• You can also access properties using square brackets
3
''
OBJECT
• Creating objects using
literal notation:
OBJECT
• Constructor Notation
4
''
OBJECT
• Updating an Object:
OBJECT
• First, create the template with the object's properties and methods.
5
''
OBJECT
• Constructor Function
property or method
OBJECT
• Constructor Function
• Each statement that creates a new property or method for this object ends
in a semicolon (not a comma, which is used in the literal syntax).
• The name of a constructor function usually begins with a capital letter (unlike
other functions, which tend to begin with a lowercase character).
• The uppercase letter is supposed to help remind developers to use the new
keyword when they create an object using that function.
6
''
OBJECT
• Creating instances of the object using the constructor function.
• The new keyword followed by a call to the function creates new object.
• The properties of each object are given as arguments to the function.
OBJECT
7
''
OBJECT
• Create & access objects
constructor notation
OBJECT
• Adding and removing properties
8
''
OBJECT
9
''
OBJECT
• Arrays are objects:
• Arrays are a special type of objects
OBJECT
• You can combine arrays and objects to create complex data structures.
10
''
OBJECT
OBJECT
11
''
OBJECT
• What are built-in objects?
• Browsers come with a set of built-in objects that act like a toolkit for creating
interactive web pages.
• The objects you create will usually be specifically written to suit your needs.
• Built-in objects contain functionality commonly needed by many scripts.
• Built-in objects help you get a wide range of information such as the width of the
browser window, or the length of text a user entered into a form field.
• You access their properties or methods using dot notation, just like you would access
the properties or methods of an object you had written yourself.
OBJECT
• Three groups of Built-in Objects:
• Browser Object Model:
• Contains objects that represent the current browser window or tab. It
contains objects that model things like browser history and the device's
screen.
• Document Object Model:
• Uses objects to create a representation of the current page. It creates a new
object for each element (and each individual section of text) within the
page.
• Global JavaScript Objects:
• Represent things that the JavaScript language needs to create a model of.
For example, there is an object that deals only with dates and times.
12
''
OBJECT
• Browser Object Model:
OBJECT
• Document Object Model:
13
''
OBJECT
• Global JavaScript Objects:
OBJECT
• Dear Students:
14
''
15
"CIT-UoB" ""
JAVASCRIPT
Haider M. Habeeb
JAVASCRIPT
1
"CIT-UoB" ""
ATTENTION
• You are required to read chapter four of the
reference.
DOM
• how JavaScript can access and update the contents of a web page while it is in
the browser window.
2
"CIT-UoB" ""
DOM
DOM
• Types of Nodes:
1. The Document Node
• Represents the entire page
2. Element Nodes
• Describe the structure of an HTML page.
3. Attribute Nodes
• Part of the element
4. Text Nodes
• It can be reached during the element
3
"CIT-UoB" ""
DOM TREE
• Body Of HTML
Page
DOM TREE
4
"CIT-UoB" ""
1. Locate the node that represents the element you want to work with.
• DOM Queries
1. Select an Individual Element Node
5
"CIT-UoB" ""
DOM TREE
• SELECT AN INDIVIDUAL ELEMENT NODE
1. getElementByld()
• Uses the value of an element's id
attribute
2. querySe1ector()
• Uses a CSS selector, and returns the first
matching element.
3. Traversing from one element to
another within the DOM tree
DOM TREE
• SELECT MULTIPLE ELEMENTS (NODELISTS)
1. getElementsByClassName()
• Selects all elements that have a specific
value for their class attribute.
2. getElementsByTagName()
• Selects all elements that have the specified
tag name.
3. querySelectorAll()
• Uses a CSS selector to select all matching
elements.
6
"CIT-UoB" ""
DOM TREE
• TRAVERSING BETWEEN ELEMENT NODES
• parentNode
• Selects the parent of the current
element node.
• previousSibling / nextSibling
• Selects the previous or next sibling from
the DOM tree.
• firstChild / lastChild
• Select the first or last child of the current
element.
DOM TREE
• STEP 2: WORK WITH THOSE ELEMENTS
• Access / Update Text Nodes
• nodeValue
• This property lets you access or update
contents of a text node.
• To access the text node on the right:
• 1. Select the <l i >element
• 2. Use the firstChild property to get the text
node
• 3. Use the text node's only property
(nodeValue) to get the text from the
element
7
"CIT-UoB" ""
DOM TREE
• STEP 2: WORK WITH THOSE ELEMENTS
• Work With HTML Content
• innerHTML
• textContent
DOM TREE
• STEP 2: WORK WITH THOSE ELEMENTS
• Access Or Update Attribute Values
• className /id
• Lets you get or update the value of the cl ass
and id attributes.
• hasAttribute()
• checks if an attribute exists.
• getAttribute()
• gets attribute’s value.
• setAttribute()
• updates the value.
• removeAttribute()
• removes an attribute.
8
"CIT-UoB" ""
DOM TREE
• querySelector(‘css selector’)
DOM TREE
• getElementsByTagName(‘tagName’)
• querySelectorAll(‘css selector’)
9
"CIT-UoB" ""
DOM TREE
• Selecting elements using id attributes
DOM TREE
• NodeLists: DOM queries that return more than one element
• When a DOM method can return more than one element, it returns a Nodelist (even
if it only finds one matching element).
• Nodelists look like arrays and are numbered like arrays, but they are not actually
arrays; they are a type of object called a collection.
10
"CIT-UoB" ""
DOM TREE
DOM TREE
11
"CIT-UoB" ""
DOM TREE
DOM TREE
12
"CIT-UoB" ""
DOM TREE
• Array syntax.
DOM TREE
• The Item() Method:
13
"CIT-UoB" ""
DOM TREE
• Array Syntax
DOM TREE
• SELECTING ELEMENTS USING CLASS ATTRIBUTES
14
"CIT-UoB" ""
DOM TREE
• SELECTING ELEMENTS BY TAG NAME
DOM TREE
• SELECTING ELEMENTS USING CSS SELECTORS
15
"CIT-UoB" ""
DOM TREE
• LOOPING THROUGH A NODELIST
16