IP - Chapter 4

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 85

Internet Programming

DYNAMIC HTML / DOM / JAVASCRIPT/ JQUERY


DHTML
Stands for Dynamic HTML
It refers to the combination of HTML, CSS, DOM and JavaScript.
According to the World Wide Web Consortium (W3C): "Dynamic
HTML is a term used by some vendors to describe the combination
of HTML, style sheets and scripts that allows documents to be
animated."
THE DOM
Document Object Model
is a platform and language-neutral interface that allows programs and
scripts to dynamically access and update the content, structure, and
style of a document.
It defines a standard for accessing documents.
When a web page is loaded, the browser creates a Document Object
Model of the page.
It defines the objects and properties of all document elements, and
the methods to access them.
HTML DOM
The HTML DOM is a standard object model and programming
interface for HTML.
It defines:
◦ HTML elements as objects,
◦ The properties of all HTML elements,
◦ The methods to access all HTML elements,
◦ The events for all HTML elements
It’s a standards for how to get, change, add or remove HTML
elements.
HTML DOM
According to HTML DOM, everything in an HTML document is a
node.
The HTML DOM says:
◦ The entire document is a document node.
◦ Every HTML tag is an element node.
◦ The text in the HTML elements are text nodes.
◦ Every HTML attribute is an attribute node.
◦ Comments are comment nodes
HTML DOM
The DOM model is constructed as
a tree of objects or nodes.
The programming interface to the
DOM is defined by standard
properties and methods
Property is a value that you can
get or set.
Method is an action you can do.
HTML DOM Access Nodes
You can access every node in an HTML document using the DOM.
You have 3 ways of doing so:
◦ Using the getElementById() method.
◦ Using the getElementsByTagName() method.
◦ Using node relationships [parentNode, firstChild, lastChild]
HTML DOM Methods
document.getElementById(“id”)- returns the element with the specified
ID.
document.getElementByTagName(“tag”)- returns all elements of that tag.
The elements in the returned list can be accessed through an index.
x.appendChild(node)- inserts a child node to x. [x is an HTML element
object]
x.removeChild(node)- remove a child node from x
HTML Properties
x.innerHTML- refers to the inner text value of x, used when getting
or setting the content of HTML elements.
x.nodeName- the name of the HTML element x.
x.nodeValue- the value of x.
X.parentNode- refers to the parent node of x.
x.childNodes- refers to the child nodes of x.
x.attributes- refers to the attribute nodes of x.
HTML DOM
The following syntax shows how you can use the DOM to accomplish
some common tasks.
Changing the attribute of an HTML element
◦ Syntax: document.getElementById(id).attribute= newValue;
◦ E.g. document.getElementById(“mylink”).href=“aboutUs.html”;
Changing the style of an HTML element
◦ Syntax: document.getElementById(id).style.property= newValue;
◦ E.g. document.getElementById(id).style.color= “red”;
DOM Objects
Window Object- is the top level object in the JavaScript hierarchy. The Window object
represents a browser window
Document Object: represents the entire HTML document and can be used to access all
elements in a page. The Document object is part of the Window object and is accessed
through the window.document property.
Navigator Object: is actually a JavaScript object, not an HTML DOM object that contains
information about the client browser
Screen Object: also a JavaScript object that contains information about the client's
display screen.
History Object: is actually a JavaScript object, not an HTML DOM object. It consists of an
array of URLs. These URLs are the URLs the user has visited within a browser window.
It’s part of the Window object and is accessed through the window.history property.
Client Side Scripts
Scripting Languages
◦ Are subsets of programming languages.
◦ Are not complied but rather interpreted.
◦ There are 2 groups of script languages on the web: client side script and
server side script.
Client Side scripts
refers to the class of computer programs on the web that are executed
client-side ( by a web browser), as opposed to server-side (on the web
server).
is an important part of the Dynamic HTML (DHTML) concept, enabling
web pages to be scripted; that is, to have a different content depending on
different conditions.
Don’t have access to the user’s computer beyond the web browser
application.
Puts less stress on the server because they don’t require processing on the
server once they’re downloaded.
JavaScript
is a client side scripting language
is an interpreted language (means that scripts execute without
preliminary compilation)
was designed to add interactivity to HTML pages
is usually embedded directly into HTML pages
JavaScript
With the help of the DOM, JavaScript gets all the power it needs to
create dynamic HTML:
◦ JavaScript can put dynamic text into an HTML page
◦ JavaScript can change attributes of HTML elements
◦ JavaScript can change CSS styles of HTML elements
◦ JavaScript can add new and remove existing HTML elements and attributes
◦ JavaScript can react to all existing HTML events in the page
◦ JavaScript can be used to validate form data
◦ JavaScript can be used to detect the visitor's browser
◦ JavaScript can be used to create cookies
Embedding JavaScript
You can place any number of scripts in an HTML document
JavaScript can be placed in the <head> tag, in the <body> tag or in external files.
JavaScript in <head> and/or <body>, the code must be inserted between
<script> and </script> tags.
Scripts that are defined outside of a function will be executed while the page is
loading.
Scripts that are defined in a function are executed when "asked" for.
Placing scripts at the bottom of the <body> element improves page load,
because HTML display is not blocked by scripts loading.
Embedding JavaScript
External JavaScript File- useful when the same code is used in
different web pages.
Pros: It separates HTML and script code. It makes HTML and JavaScript
easier to read and maintain. Cached JavaScript files can speed up page
loads.
The files have a .js extension.
The <script> tags aren’t included when writing external scripts.
You then place the script reference in the <head> or <body> section of
the HTML document.
JavaScript Miscellaneous
JavaScript statements are terminated with a semicolon.
It’s a case-sensitive language.
Whitespaces are ignored.
Comments: // single line comment
/* multi line comment */
JavaScript Output
JavaScript doesn’t have any built-in print or display functions.
JavaScript Display Possibilities
◦ Writing into an alert box, using window.alert()
◦ Writing into the HTML output using document.write()
◦ Writing into an HTML element using innerHTML
◦ Writing into the browser console, using console.log()
Output: document.write()
For testing purposes, it is convenient to use document.write()
Using document.write() after an HTML document is fully loaded, will
delete all existing HTML.
Output: window.alert()
You can use an alert box to display data.
Output: innerHTML
The innerHTML property defines an HTML element content.
Output: console.log()
Can be used to display data in the browser console.
You can view the browser console by pressing F12 or by right-clicking
and selecting the inspect option (ctrl+shift+i).
JavaScript Dialog Boxes
JavaScript Variables
The var keyword is used to define variables.
Can hold a value of any data type
A variable may or may not be declared before usage
Must begin with a letter or an underscore character and should not
start with a numeral (0-9)
JavaScript Literals
Numbers are written with or without decimals: 10.01 or 10
Strings are text, written within double or single quotes: "John Doe“
or 'John Doe'
NaN - is a JavaScript reserved word indicating that a value is not a
number
JavaScript Datatypes
JavaScript allows the same variable to contain different types of data values.
Primitive data types
◦ Number: integer & floating-point numbers
◦ Boolean: logical values “true” or “false”
◦ String: a sequence of alphanumeric characters

Composite data types (or Complex data types)


◦ Object: a named collection of data
◦ Array: a sequence of values

Special data types


◦ Null: an initial value is assigned
◦ Undefined: the variable has been created by not yet assigned a value
typeof() method
The typeof operator is used to find out the type of a JavaScript
variable.
Operators
Arithmetic Operators: +, -, *, /, %, ++, --
Assignment Operators : =,+=, -=, *=, /=, %=
Comparison Operators: >, =, <=, ==, ===, !=, !==
Bitwise Operators: &, |, ~, <>
String Operators: +
Conditional Statements
JavaScript have the following conditional statements:
◦ Use if to specify a block of code to be executed, if a specified
condition is true
◦ Use else to specify a block of code to be executed, if the same
condition is false
◦ Use else if to specify a new condition to test, if the first condition is
false
◦ Use switch to specify many alternative blocks of code to be
executed
Loops
JavaScript supports different kinds of loops:
◦ for: loops through a block of code a number of times
◦ for/in: loops through the properties of an object
◦ for/of: loops through the values of an object
◦ while: loops through a block of code while a specified condition is
true
◦ do/while: also loops through a block of code while a specified
condition is true. Conditional block executes at least once.
for/in loop
loops through the properties of an object.
for/of loop
loops through the values of an object.
Loop controls
Break: used to jump out of a loop or a switch block. It breaks the
loop and continues executing the code after the loop (if any)

Continue: breaks the current iteration (in the loop), if a specified


condition occurs, and continues with the next iteration in the loop.
Array
Creating an array:
var arrayName=[val1, val2, val3….]; or
var arrayName= new Array (val1, val2,val3…);
Array can hold different objects/datatypes.
Uses numbers (indexes) to access its elements.
Array index starts with 0.
Array Properties and Methods
The length property: returns the length of an array

Adding Array Elements: the easiest way to add a new element to an


array is using the push method:

Sorting Array Elements: sorts elements in ascending order.


JavaScript Functions
Function syntax:
Function Invocation: The code inside the function will only executes
when the function is called/ 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.
JavaScript Events
HTML Events: can be something the browser does, or something a
user does
Some examples of HTML events
◦ An HTML web page has finished loading
◦ An HTML input field was changed
◦ An HTML button was clicked
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
onload and onunloadEvent
onload onunload
occurs when an object has been loaded occurs once a page has
unloaded
is most often used with the <body> element to
execute a script once a webpage has completely occurs when the user
loaded all content navigates away from the page
(by clicking on a link,
can be used to check the visitor's browser type
submitting a form, closing the
and browser version, and load the proper version browser
of the web page based on the information
can also be used to deal with cookies
onsubmit Event
occurs when you try to submit a form, often used to trigger a form
validator function
In the following example: if validate() function returns true, the form
will be submitted, otherwise it will not submit the data.
onmouseover and onmouseout
The onmouseover event triggers when you bring your mouse over
any element.
The onmouseout event triggers when you move your mouse out
from an element.
onFocus, onBlur, onChange Events
The onFocus, onBlur and onChange events are often used in
combination with validation of form fields
Example:
<input type="text“ id="email" onchange="checkEmail()">
More HTML Events
Event Description
ontouchstart occurs when a finger is placed on a touch screen
onclick occurs when a finger is placed on a touch screen
onplay occurs when a media has been started
onoffline occurs when the browser starts to work offline
onkeydown occurs when the user pushes a keyboard key
ondblclick occurs when the user double-clicks on an element
oninput occurs when an element gets user input
ondrag occurs when an element is being dragged
oncopy occurs when the user copies the content of an element
onbeforeprint occurs when a page is about to be printed
JavaScript Objects
JavaScript objects are containers for
named values.
Accessing Object properties:
objectName.propertyName or
objectName["propertyName"]
Accessing Object Methods:
objectName.methodName()
JavaScript Strings
A string can be any text inside quotes. You can use single or double
quotes.
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string or you can use escape characters.
Other escape characters: \’ , \” , \\ , \n, \t ….
The length of a string is found in the built in property length.
More String Methods
Method Description
charAt() Returns the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined
strings
match() Searches a string for a match against a regular expression
and returns the matches.
toLowerCase() Converts a string to lowercase letters
trim() Removes whitespace from both ends of a string
split() Removes whitespace from both ends of a string
JavaScript Date
A date consists of a year, a month, a day, an hour, a minute, a
second, and milliseconds.
Date objects are created with the new Date() constructor
Using new Date(), creates a new date object with the current date
and time
When you display a date object in HTML, it is automatically
converted to a string, with the toString() method.
Date Methods
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMonth () Get the month (0-11)
JavaScript Regular Expressions
A Regular Expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe
what you are searching for.
The JavaScript RegExp class represents regular expressions.
Syntax: var pattern = /pattern/attributes; or
var pattern = new RegExp(pattern, attributes);
pattern: A string that specifies the pattern of the regular expression or another
regular expression.
attributes: An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multiline matches, respectively.
Regular Expression Patterns
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
Regular Expression Patterns
MetaCharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning or at the end of a word
Regular Expression Patterns Examples
Expression Description
x{N} It matches any string containing a sequence of N x’s
y{2,3} It matches any string containing a sequence of two or three y’s.
m{2, } It matches ant string containing a sequence of at least two m’s.
k$ It matches any string with k at the end of it.
^z It matches any string with z at the beginning of it.
Using the RegExp Object
In JavaScript, the RegExp object is a regular expression object with
predefined properties and methods.
Using the RegExp method test() :
It searches a string for a pattern, and returns true or false,
depending on the result.
The following example searches a string for the character "e":
Using the RegExp Object
Using the RegExp method exec():
It searches a string for a specified pattern, and returns the found
text.
If no match is found, it returns null.
The following example searches a string for the character ‘e’
Using Regular Expressions
Using string search() with a regular expression:
Use a regular expression to do a case-insensitive search for “best” in
a string:
Using Regular Expressions
Use string match() with a regular expression:
Searches a string for a match against a regular expression, and
returns the matches, as an array object or returns null if no match if
found.
JavaScript Page Refresh
 A web page can be refreshed using JavaScript location.reload
method
The method can be called automatically upon an event or simply
when the user clicks on a link.
<a href="location.reload(true);">Refresh Page</a>
Auto Refresh
◦ setTimeout() is a built-in JavaScript function which can be used to
execute another function after a given time interval
JavaScript Page Redirection
There could be various reasons why you would like to redirect a user
from the original page
1. You did not like the name of your domain and you are moving to a
new one.
2. You have built-up various pages based on browser versions or
their names or may be based on different countries, then you can
use client-side page redirection to land your users on the
appropriate page.
3. Etc…
*You can redirect visitors to different
pages based on their browser type.
Page Redirection Use the navigator object.
Auto redirect a page using window.location
<body onload="window.location='www.google.com';">
Auto redirect a page after sometime using setTimeOut.
JavaScript Print Page
The JavaScript print function window.print() prints the current web
page when executed.
Cookies
are small files which are stored on a user's computer
are designed to hold a modest amount of data specific to a
particular client and website.
Each cookie is effectively a small lookup table containing pairs of
(key, data) values.
can be accessed either by a client side or server side script language
Cookies: why?
When a web server has sent a web page to a browser, the connection is
shut down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember
information about the user”.
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
When a browser request a web page from a server, cookies belonging to
the page is added to the request. This way the server gets the necessary
data to "remember" information about users
Cookies
Cookies are a plain text data record of 5 variable-length fields:
◦ Expires: The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
◦ Domain: The domain name of your site.
◦ Path: The path to the directory or web page that set the cookie. This may be
blank if you want to retrieve the cookie from any directory or page.
◦ Secure: If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
◦ Name: The name of the cookie
◦ Value: The data that is going to be stored on the cookie
JavaScript Cookies
JavaScript can create, read, and delete cookies with the
document.cookie property.
With JavaScript, a cookie can be created like this:
document.cookie="username=John Doe;”
You can also add an expiry date. By default, the cookie is deleted when
the browser is closed:
document.cookie="username=John Doe; expires=Fri,31 Dec 2021
12:00:00 UTC;”
JavaScript Cookies
Read a Cookie with JavaScript: cookies can be read like this:
var x = document.cookie;
document.cookie will return all cookies in one string like:
cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript: you can change a cookie the same way as you create it:
document.cookie="username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC;
path=/";
Delete a Cookie with JavaScript: to delete a cookie set the expires parameter to a passed
date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
Set Cookie: Example
Read Cookie: Example
jQuery
Introduction to jQuery
jQuery is a lightweight, “write less, do more” JavaScript library.
The purpose of jQuery is to make it much easier to use JavaScript on
your website.
jQuery takes a lot of common tasks that require many lines of
JavaScript code to accomplish, and wraps them into methods that
you can call with a single line of code.
Introduction to jQuery
The jQuery library contains the following features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX, Utilities
In addition, jQuery has plugins for almost any task out there.
Adding jQuery to webpages
There are two ways to start using jQuery on your web site
You can:
◦ Download the jQuery library from jQuery.com and reference it in your page
within the script tag.

◦ Include jQuery from a CDN, like Google


Syntax
The jQuery syntax is tailor made for selecting HTML elements and
performing some action on the elements(s)
Basic syntax is: $(selector).action()
A $ sign to access jQuery
A selector to locate or find HTML elements
An action to be performed on the selected elements.
The document ready Event
All jQuery methods are usually defined inside a documents ready
event:

This helps to prevent any jQuery code from running before the
document is finished loading (is ready).
Alternatively:
jQuery Selectors
jQuery selectors are used to "find" (or select) HTML elements based
on their id, classes, types ….
It's based on the existing CSS Selectors, and in addition, it has some
own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $()
The element selector [$(‘p’)], #id selector [$(‘#test’)], .class selector [$
(‘.test’)] …
More: jQuery Selectors
$("*"): Selects all elements
$"p.intro"): Selects all <p> elements with class="intro"
$("ul li:first"): Selects the first <li> element of the first <ul>
$("ul li:first-child"): Selects the first <li> element of every <ul>
$("[href]"): Selects all elements with an href attribute
$("a[target='_blank']"): Selects all <a> elements with a target attribute value
equal to "_blank"
$(":button"): Selects all <button> elements and <input> elements of
type="button"
jQuery Event Methods
jQuery is tailor-made to respond to events in an HTML page
jQuery Syntax For Event Methods
To assign a click event to all paragraphs on a page, you can do this:
$("p").click();
The next step is to define what should happen when the event fires.
You must pass a function to the event:
Or you can use the “on” method:
jQuery Event Methods
$(document).ready() :allows you to execute a function when the
document is fully loaded
click(): executed when the user clicks on the HTML element.
dblclick(): executed when the user double-clicks on the HTML
element.
mouseenter(), mouseleave(), mousedown(), mouseup(), hover(),
focus(), blur(), on()
jQuery Effects: Hide/ Show
Syntax: $(selector).hide(speed,callback);
$(selector).show(speed,callback);
$(selector).toggle(speed,callback);
The optional speed parameter specifies the speed of the
hiding/showing, and can take the following values: "slow", "fast", or
milliseconds.
The optional callback parameter is a function to be executed after
the hide() , show() or toggle() method completes.
jQuery Effects: Fade
With jQuery you can fade an element in and out of visibility.
jQuery has the following fade methods:
◦ fadeIn(speed,callback) is used to fade in a hidden element.
◦ fadeOut(speed,callback) is used to fade out a visible element
◦ fadeToggle(speed,callback) toggles between the fadeIn() and
fadeOut() methods
◦ fadeTo(speed,opacity,callback) allows fading to a given opacity
(value between 0 and 1)
jQuery Effects: Slide
With jQuery you can create a sliding effect on elements.
jQuery has the following slide methods:
◦ slideDown(speed, callback) is used to slide down an element
◦ slideUp(speed, callback) is used to slide up an element
◦ slideToggle() toggles between slide up and slide down.
jQuery DOM Manipulation
jQuery offers the following methods for DOM manipulation:
◦ text() - Sets or returns the text content of selected elements
◦ html() - Sets or returns the content of selected elements (including
HTML markup)
◦ val() - Sets or returns the value of form fields
◦ attr() – Sets or returns attribute values
jQuery Add Elements
With jQuery, it is easy to add new elements/content.
Four jQuery methods that are used to add new content:
append() - Inserts content at the end of the selected elements
prepend() - Inserts content at the beginning of the selected
elements
after() - Inserts content after the selected elements
before() - Inserts content before the selected elements
jQuery Remove Elements
To remove elements and content, there are mainly two jQuery
methods:
remove() - Removes the selected element (and its child elements)
◦ also accepts one parameter, which allows you to filter the elements to be
removed.
◦ The parameter can be any of the jQuery selector syntaxes.
empty() - Removes the child elements from the selected element
jQuery CSS
jQuery has several methods for CSS manipulation. We will look at the
following methods:
addClass() - Adds one or more classes to the selected elements
removeClass() - Removes one or more classes from the selected elements
toggleClass() - Toggles between adding/removing classes from the selected
elements
css() - Sets or returns one or more style properties for the selected
elements
Syntax: css("propertyname"); & css("propertyname","value");
Reading Assignment
JavaScript Math function
jQuery Callback functions
jQuery method chaining
jQuery Animate
jQuery AJAX

You might also like