html / xhtml - eienflaw/eie4432sem12017-18/ref_client.pdf · html/xhtml 1 html hypertext mark-up...
TRANSCRIPT
HTML/XHTMLHTML/XHTML
1
HTML HyperText Mark-up Language
Basic language for WWW documentsg g Format a web page’s look, position graphics and
multimedia elements Describe document structure and formatting Describe document structure and formatting
Platform independent: High-level language, No machine code
HTML is rendered to a graphic format by the browser
k t markup tags suggests the Web browser how to display the page
2
HTML / XHTML HTML:
Loose syntax Few syntactic rules: not enforced by Few syntactic rules: not enforced by
HTML processors Browsers are “forgiving” Browsers are forgiving
XHTML: Stricter syntax
HTML tag/attribute: lowercase
3
HTML 1995: HTML 2.0: simple 1997: HTML 3 2: Standardized by the World Wide Web 1997: HTML 3.2: Standardized by the World Wide Web
Consortium (W3C) Proprietory tags
1999: HTML 4.01, A clean up of 4.0 3 variations: strict transitional frameset 3 variations: strict, transitional, frameset
2000: XHTML 1.0 (x: extensible) Reformation of HTML 4.01 using XML, strict syntaxg y No new elements/attributes, difference: syntax
2001: XHTML 1.1: drop framesXHTML 2 0 id b k d ibl b d d
4
XHTML 2.0: idea: not backward compatible , abandoned HTML 5, 2008
HTML5: design principles Compatibility
B k d tibl Backward compatible Utilityy
Render correctly: id=“myname” id=Myname ID=“myname” id= myname , id=Myname, ID= myname
Interoperabilityl f E d f Simplify syntax, e.g., DOCTYPE definition
Precise specification: well-defined behavioursp Aim: browser interoperability
5
HTML5: design principles
Universal access Support users with disabilities Html5 work across all devices and platforms Html5 work across all devices and platforms
Reduce the need for external plugins More markup to replace scripting Device independent (PC iPhone Android) Device independent (PC, iPhone, Android)
6
Basic Structure of HTML5Basic Structure of HTML5ifi h l i
<!DOCTYPE html><html>
Specifies html version browser renders it properly
<html><!-- This is comment --><head>
<title> This is title, describing the content </title></head><body><body>
This is body, main part of the page</body>/body
</html>
7
HTML – tree structure Indentation <!DOCTYPE html>D E m
<html><head>
<title> My title </title></head><body><body>
<h1> My header </h1><a href=“”> My link </a>y
</body></html>
8
HTML Syntax HTML: consists of a tree of HTML elements
Each element begins with a start tag, ends with an end tag
An element can define attributes within its start tag
9
HTML Information is generally enclosed inside
paired tags paired tags Like <tag> information </tag>
Example: Example: Paragraph tag: <p> and </p>
Tells browser this is a paragraph, and the presentation is left to the browser to determinethe browser to determine
Line break: <br /> Marks a line break within phrasing content
Commonly used tags Commonly used tags Less than 50 tags
Practice!!10
Practice!!
Common Tags
XHTML: Extensible HyperText Markup
LanguageLanguage Stricter and cleaner
si f HTMLversion of HTML
11
Syntax Rules XHTML documents must be well-formed
Must have basic structure <html> <head> <title> </title> </head> <head> <title>… </title> </head> <body> … </body> </html>
Sub elements must be in pairs and correctly nested <b> It is <i> italic </b></i> <b> It is <i> italic </b></i> Should be rewritten as <b> It is <i> italic </i> </b>
12
Syntax Rules All XHTML elements must be closed, in
lower case <p> … </p> <br /> <hr /> <img src=“…” /> Remember the extra space before “/”p
13
Syntax Rules Attribute minimization is forbidden
Wrong: Wrong: <input checked>, <option selected>
Correcti t h k d “ h k d” / <input checked=“checked” />
<option selected=“selected”> Tag names must be in lowercaseg Attribute values must be quoted
Wrongbl D H “100%” bl d h 100% <table WIDTH=“100%”> , <table width=100%>
Should be <table width=“100%”>
14
C di St l Sh tCascading Style Sheet
15
Styles?
http://www.eie.polyu.edu.hk/~nflaw/Biclustering/index.htmlRequest string:
GET /~nflaw/Biclustering/index html HTTP/1 1GET /~nflaw/Biclustering/index.html HTTP/1.1Host: www.eie.polyu.edu.hk
Response string:Response string:HTTP/1.1 200 OK Server: Apache/1.3.20 Content-type: text/html <html><head> <title>Main Page</title><style type=“text/css”><style type= text/css >
h1 {font-size: 20pt}p {text-indent: 1cm}
16
</style></head> <body>….. </body></html>
Styles as Tag Attributes Attributes such as bgcolor
<body bgcolor=“red”> … Mix content and presentation Mix content and presentation Difficult to manage / inconsistentCSS d d i CSS: separate data and presentation CSS 2.1 (June 2011) ( ) CSS 3
17
Syntax
STYLE = SELECTOR {RULES}S YLE SELE OR {RULES} Selector: HTML elements
Rule: how the style changes Rule: how the style changes RULES = NAME:VALUE; NAME:VALUE; … Example:
p { p {color: white;background-color: blue;
} 18
Style Attribute Inline style:
Style = “CSS Style rule” <p style=“color:white; <p style= color:white;
background-color: blue”>A h /A paragraph </p>
“local” effect Apply to that <p> only, not other <p> tags
19
Embedded Style Sheet Define in the head section using the
style element Consistent styling throughout the doc Consistent styling throughout the doc
Example:h d l l / l<head> <title> example </title>
<style type=“text/css”y ypp { color: white;
background-color:blue}background-color:blue}</style> </head> 20
External Style Sheet Contain styles in another file (*.css)
Separate content from presentation Consistent style for all pages in a web site Consistent style for all pages in a web site
Place a link in the head sectionl k l “ l h ” h f “ l ” / <link rel=“stylesheet” href=“sample.css” />
21
<head> Separate Stylesheet...<link rel="stylesheet" type="text/css" href="myStyles.css" /><style type="text/css">
Separate Stylesheet
<style type= text/css >body {
font-family: Tahoma, Arial, sans-serif;...
}</style>
S f S ly
</head><body>
Page-Specific Styles
...<div style="padding:2px; ... ">...
Element-Specific Styles
22
</body>
“Cascade” Most specific elements most
precedence Order: Order:
Inline, embedded, externald l "b k d l " <td style = "background-color: green"><p style = "background-color: red"> p y g
Hello, World</p></td>will display with red background colorwill display with red background color
23Ref - CSS
“Cascade”
From Web Style Guide: Basic Design Principles for Creating Web Sites by
24
From Web Style Guide: Basic Design Principles for Creating Web Sites, by Patrick J. Lynch and Sarah Horton. http://webstyleguide.com/wsg3/index.html
Syntax: SELECTOR {RULES}
Group selector:pp, h3, h4 {color: white;
background-color:blue}background-color:blue} Universal selector (applies to all HTML
l )elements):* {font-weight: bold} { g }
descendent selector {f t i 12 }p span {font-size: 12px}
25
Syntax: SELECTOR {RULES} Class Selectors
Apply to HTML element where the attribute CLASS is specifiedp
Example: in head section p style1 {color:#FF0000} p.style1 {color:#FF0000}
In body section l “ t l 1” d l t t / <p class=“style1”> red color text </p>
26
Syntax: SELECTOR {RULES} Generic Selectors
Apply to HTML element where the attribute CLASS is specifiedp
Example: in head section style2 {color:#FF0000} .style2 {color:#FF0000}
In body section l “ t l 2” d l t t / <p class=“style2”> red color text </p>
<h1 class=“style2”> red heading </h1>
27
Syntax: SELECTOR {RULES} ID Selectors
Apply to HTML element identified by specific IDp
Example: in head section# R d { l #FF0000} p#paraRed {color:#FF0000}
In body sectiony <p id=“paraRed”> red color text </p>
28
Pseudo classes Styles that apply when sth happens :hover
a:hover {color:#FF00FF} a:hover {color:#FF00FF} hover class applies when the mouse
i th l tcursor is over the element
29
Pseudo classes Unvisited link
li k { l #FF0000} a:link {color:#FF0000} Visited link
a:visited {color:#00FF00} Selected link Selected link a:active {color:#0000FF}
Other browsers a:focus {color:#0000FF}
focus class applies when an element has focus in IE 30
Descendant selectors h1 { color: red } em { color: green } h1 em { color: blue } h1 em { color: blue }
<h1>Hello</h1><p>This <em>is a test</em></p><p>This <em>is a test</em></p><h1><em>This</em> <span>headline is </span>
<em>very important </em> </h1>31
Difference between padding Difference between padding, border and margin
<style type="text/css">y yp.box { width: 280px; height: 200px;
padding: 10px; border: 1px solid; }margin: 15px; }
</style>…<p> Original paragraph with no style; … </p><p class="box"> Paragraph with style; Paragraph … </p><p> Original paragraph with no style; … </p>
32Effective width = 15+1+10+280+10+1+15= 312px
Question 1Question 1<style type="text/css"><style type= text/css >
body{color: blue;}h1{font-style: italic;}h1{font-style: italic;}p{text-decoration: underline;} my {font-size: 150%;}.my {font-size: 150%;}
</style>
…<h1>Simple</h1><h1>Simple</h1><p>A big example</p>< >A < l " ">bi </ > l </ >
33
<p>A <span class="my">big </span> example</p>
Question 2 What styles are applied to the text
node containing the word “big”?node containing the word big ?<style type="text/css">
body {color: blue;}body {color: blue;}h1,p {color: orange;}p {text decoration: none;}p {text-decoration: none;}.my {text-decoration: underline}
</ t l ></style>…
h1 Si l /h134
<h1>Simple</h1><p> A <span class="my"> big </span> example </p>
Alternate stylesheet<head>
<meta http-equiv=“X-UA-Compatible”eta ttp equ U Co pat b econtent=“IE=EmulateIE9”>
<link rel="stylesheet” href="page.css" media="all" t "t t/ " /type="text/css" />
<!--[if gt IE 6]><link rel="stylesheet" href="ie7 css" media="all"<link rel= stylesheet href= ie7.css media= all
type="text/css" /><![endif]-->
…<p class="test"> this is a paragraph. </p>
35
Alternate stylesheetpage.css:
* test {font size: 18px;}*.test {font-size: 18px;}
ie7 css:ie7.css:
* test {border: 2px solid black; background color:*.test {border: 2px solid black; background-color: gold; }
36
Alternate stylesheet
37
Summary Web page
HTML/XHTML: content Cascading Style Sheet (CSS): style and layout Inline, embedded, external Class + ID
Next HTML5 HTML5 JavaScript
38
HTML 5HTML 5
39
Browser compatibility www.findmebyip.com
40
www.caniuse.com
41
div Separate semantics (meaning and
structure) from presentation (formatting)(formatt ng)
Div: used to identify different parts f d um nt f diff nt of a document for different
formatting HTML: new elements to replace
typical divstypical divs42
Example of a document p fstructure
<header>
<nav>
<article>
<section><aside>
<section>
<footer>
43
<footer>
Example of a document p fstructure
44
HTML5 Structure <section>: logical division of the
document <article>: purpose: identify portions <article>: purpose: identify portions
of the document that you want to be ind p nd nt nd dist ibut bl f m independent and distributable from the rest of the document
<aside>: sidebar discussion <header>: section header <header>: section header <nav>: navigational aids 45
<!DOCTYPE html><html><head> <title> Document structure </title> </head><body><body>
<header><span style="color:red; font-style: italic"> Lecture 1 p y ; f y</span><hr />
/h d</header><nav>
<a href="HTML html" target=" blank"> HTML </a> | <a href= HTML.html target= _blank > HTML </a> | <a href="CSS.html" target="_blank"> CSS </a> | <a href="JS.html" target="_blank"> JavaScript </a>
</nav><h1> Client-side Techniques </h1>h2 HTML /h2
47
<h2> HTML </h2>
<aside style="font-style: italic; color: blue; float: right; width:120px">To learn programming well you have to write programs yourselfTo learn programming well, you have to write programs yourself
</aside><p> HTML stands for HyperText MarkUp Language ... </p>p yp p g g p<p> HTML 5 has new structural tags </p>
<footer> © 2012 </footer></body>
</html>
48
HTML 5 FHTML 5 Forms
49
Syntax
Fieldset: group related elements in a form (draws Fieldset group related elements in a form (draws a box around those elements)
Legend: create a text label within fieldset Legend: create a text label within fieldset Basic structure
f id “ F ” <form id=“myForm”><fieldset>
l d f h f ld /l d<legend> Caption for the fieldset </legend><label for=“fn”> First Name </label><input id=“fn” name=“fn” type=“text” />
</fieldset> </form> 50
Syntax
The form tag attributes Action
Specifies the server-side program or script that will process the form data
<form action=“http://www.../formprocess.php”> Method
Get post
id (or name)id (or name) Identifies the form
51
IInput
<input type=“text” id=“firstName” p ypplaceholder=“input your first name” /> Placeholder: Show when the user has not yet entered y
any values <input type=“password” id=“pwd” />p yp p p <input type=“checkbox” id=“browser”>
<input type=“radio” name=“browser”> <input type= radio name= browser > Same name:
<input value=“IE”/> Internet Explorer <br /> <input … value= IE /> Internet Explorer <br /> <input … value=“FF”/> Firefox <br />
52
IInput
<select id=“browser” ><option value=“IE”> Internet Explorer </option><option value=“FF”> Firefox </option>
<select> <input type=“submit” value=“Submit” /> <input type=“reset” value=“Clear” /> input type reset value Clear / <input type=“button” value=“click” />
No default action associate with a JavaScript No default action, associate with a JavaScript function
53
E il & URLEmail & URL
<input type=“email” />V lid t ’ i t Validate user’s input Changes from browser to browserg Opera: needs to have “@” only Firefox: “(x)@(x) (x)” Firefox: (x)@(x).(x) Mobile device: on-screen keyboard
<input type=“url” />
54
N bNumbers
Traditional way: combo box Spinner control for numbers
<input id="age" name="age" <input id= age name= age type="number" min="10" max="90" step="1" value="10" /> step= 1 value= 10 />
55Firefox Opera
lidSlider Firefox
<label for="aNo"> Choose a number </label><input id="aNo" name="aNo" type="range"
i "10" "90" t "1" l "50" min="10" max="90" step="1" value="50" onchange="yNo.value=this.value" /> g y
<output name="yNo"> 50 </output>
56Opera
l Auto complete system
<datalist>: choose from the predefined options or type sth else in the text boxoptions or type sth else in the text box
57
M d fi ldMandatory fields
Keyword: requiredy q <input type=“text” required />
i t t “ il” i d <input type=“email” required placeholder=“Insert your email” /> Email must be entered before the form
can be submitted
58
R l iRegular expressions
Regular expressions: Specify a pattern for matching strings
of text E.g., phone number: 8 digits: ^\d{8}$
<input type=“text” name=“phoneNo” <input type= text name= phoneNo required pattern=“^\d{8}$” />
59
D d TiDate and Time
<input type=“date” /> <input type=“time” /> <input type=“datetime” /> <input type= datetime /> <input type=“month” /> <input type=“week” />
60
V lid i f db kValidation feedback Browser dependent
61
Summary Client-side techniques
HTML, XHTML, HTML 5 Cascading Style Sheet (CSS)
62
Cli t id T h iClient-side Techniques
JavaScriptJavaScript
63
Client-side Techniques Static web pages Interactive web page: without depending
on interaction with a server HTML/XHTML: content Cascading Style Sheet (CSS): style and layoutg y ( ) y y Script language: (JavaScript) control HTML
elements
64
JavaScript Sent to the browser as code and interpreted by the
browser (browser dependent)( p ) An interpreted language
No need to compile Codes are embedded onto the html
Within <head> (script runs before body is loaded)Within <body> (script runs as body is being loaded) Within <body> (script runs as body is being loaded)
<script type=“text/javascript”> … </script> No need to declare the variable type
var x, y; x can be integer, floating-point number, string, ...
Case sensitive
65
Case sensitive
Window object Access through JavaScript
window alert(message); window.alert(message); window.alert(“Error”);
window.open(url);// window.open(“http://www.eie.polyu.edu.hk”);
value = window.prompt(message, defaultValue); window.prompt(“Enter your student number:”, 1111);p p ( y ) User presses ok, value=inputValue User presses cancel, value is null
value = window confirm(message); value = window.confirm(message); window.confirm(“Are you sure to delete?”); Value is true if press OK, false if press cancel
66
C di i lConditionalsf ( d l) { if (conditional) {} else { } } { }
while (control_expression) { }for (init; control; increment/decrement) for (init; control; increment/decrement) { }
{ } do {statement...} while (control expression);wh le (control_express on);
67
DOM (document object model) Tree-like document representation
E d E.g. document object All elements in the document are under this
tree Represented in an object hierarchy
Examples document.all[i]: list out all elements [ ] document.myform: form with name
“myform”
68
y
Example<html> <head> <title> Example </title> </head> <body> <script type=“text/javascript”> document.writeln(‘<h1> Hello world!</h1>’); document.writeln(‘<p> This is …</p>’); </script> </body></html>
69
/
Before/after <script> executes
70<script> tags are interpreted as the page loads
html
head bodyy
title script
form pp
p p
inputinput
input
71document.getElementById(‘myform1’).firstName.value
<html> <head> <title> A simple document </title> </head>
<body> <body> <table>
<tr> <tr> <th> Breakfast </th>
<td> 0 </td> <td> 0 </td> <td> 1 </td>
/t </tr> <tr>
h L h / h <th> Lunch </th> <td> 1 </td> <td> 0 </td> </tr>
72
</table> </body>
Element Access in JavaScript DOM address
document.forms[0].elements[0] <form action=“”>
<input type=“text” />/f</form>
Element names: name attributed F 1 document.myForm.myinput1
<form name=“myForm” action=“”>i t t “t t” “ i t1” /<input type=“text” name=“myinput1” />
</form>
73
Element Access in JavaScript
getElementById method (DOM 1)g y document.getElementById(“myinput1”) <form action=“”>
<input type=“text” id=“myinput1” /></form>
74
JavaScript Function Head section
<script type=“text/javascript”><script type= text/javascript >function f(x) {
y = x*x; “ f” “ ” w = “Square of” + x + “ is” + y;
return w; }</script>/scr pt
Body:<script type=“text/javascript”>
data = f(4);data f(4);document.write(data);
</script>
75
Event-driven programming Code is executed by user interactions
Detect certain activities of the browser/user
Event:N tifi ti th t th h d Notification that sth has occurred, e.g., mouse clicking
Event handler: script executed on an event
76
Event Model Event: Something that triggers (calls
or starts) one of your functions
li k bj t li kclicks on an objectdouble-clicks on an object
onclick ondblclickj
Makes an object activeIE i fi i h d l di
onfocusl dIE: page is finished loading
A cursor moves onload onmousemoA cursor moves
A form is submittedonmousemove
ons bmit77
onsubmit
Flow Chart Web page defines event handlers Event occurs
Event object generatedj g Event handler runs
Example:Event object
Example <p …onclick=“calltoFunction(event);”> … <script type=“text/javascript”> <script type= text/javascript >
function calltoFunction(e) { …} </script>
78Event handler
Handling events <input type = “button” name = “freeOffer”
id = “freeButton” />
2 approaches: <input type = “button” name = “freeOffer” id = nput typ utton nam fr Off r
“freeButton” onclick = “freeButtonHandler();” /> document.getElementById(“freeButton”).onclick = g y ( )
freeButtonHandler;
79
Example 2: DOM + CSSExample 2: DOM + CSS body.style.backgroundColory y g
CSS: background-color: #FFFF00
80
E l 3 DOM CExample 3: DOM + CSS
81
Two different lstyles
Separate:p Content(Html) Presentation(css) Presentation(css) Behavior (JS)
82
E l 5 Example 5: onmousemove
83
E l 5 Example 5: onmousemove
84
Others onfocus:
Occurs when a user tabs into or clicks on a text field, a textarea field
onblur: Occurs when a user leaves a text field, a u w u f ,
textarea field onsubmit onsubmit
Occurs when a user submits a form
85 86
Web ApplicationsWeb Applications Multi-tier model Three tier architectures
Client tierWeb browser software that
Internt Web browser software that
interacts with the applications Middle tier
Contains most of the
et
Contains most of the application logic and communicates data between the other tiers
Database tier Consist of the database
management system that management system that manages the database containing the data users create, delete, modify and
87
query
Request-Response (HTTP)q p ( )
Client W bClient (browser)
Web Server
Request string (Html file)
Response string: HTML, CSS, JavaScriptJavaScript
Browser software: interprets the code
88
Browser software: interprets the code
F V lid tiForm Validation
Regular ExpressionRegular Expression
89
Usage Common types of validation:
E i ti fi d ith th d t th Ensuring users are satisfied with the data theyenter
Ensuring that mandatory fields have been Ensuring that mandatory fields have beencompleted
In a specified formatp Phone no: Area code + no
2 types: Field level validation Form level validation
90
Field level validation
function isNumeric(e) {( ) {…}}
……Enter number: <input type=“text” id=“noStudyHr” onblur=“isNumeric(this)” /> onblur isNumeric(this) />
91
Form level validationfunction check(f){( ){ var t = isNumeric(f.noStudyHr); if (t) return true;if (t) return true; else return false;}}function isNumeric(e) { …}
<form …onsubmit=“return check(this)”> Enter number: <input type=“text” id=“noStudyHr” /> Enter number: <input type= text id= noStudyHr /> <input type=“submit” value=“submit” /></form>
92
</form>
Regular Expression Object that describes a pattern of
characters Used for pattern matching search and Used for pattern matching, search and
replace operationsDefine regular expressions: Define regular expressions: var pattern = /s/ var pattern = new RegExp(“s”)
93
Regular Expressionfunction check(){function check(){
/ / var regexp=/s/ ; if (myform.myinput.value.match(regexp))
l t("Y i t i " f i t l ) alert("Your input is " + myform.myinput.value); else
l (" l d") alert("Invalid");
}
94
Syntax Character Classes:
[…]: any one character between the brackets [1-5]: matches “1”, “3”, but not “a”
[^…]: any one character not between the b k tbrackets [^1-5]:
\d i l [0 9]matches “a” but not “1”, “3”
\d: equivalent to [0-9] \D: equivalent to [^0-9]
95
Syntax Character Classes:
: any character except newline .: any character except newline \w: equivalent to [a-zA-Z0-9] \W: equivalent to [^a-zA-Z0-9]
Match position: ^: match the beginning of the string
^JavaScript JavaScript “JavaScript Programming” “What is JavaScript”
$: match the end of the string $: match the end of the string JavaScript$
“I love JavaScript” “JavaScript is great”
96
JavaScript is great
Regular Expression Repetition:
{n m}: match the previous item at least n times {n,m}: match the previous item at least n times but no more than m times
{n,}: match the previous item n or more timesp {n}: match exactly n occurrences of the
previous itemExample : Example : 2 digits only:
/ ^\d{2}$ /{ }$ 2 or more digits
/ ^\d{2,}$ /
97
Regular Expression Others:
(…): grouping (12)+34
1234 121234 12134 12134
|: alternation. Match either the subexpression to the left or the subexpression to the left or the subexpression to the right (12|34)+
98
( )
Regular Expression g: search for all matches
i: ignore case i: ignore case match()
Takes a regular expression as a parameter and returns an Takes a regular expression as a parameter and returns an array of all the matching strings found
Example“ E ” “test1 Test2 TEST3”
/Test[0-9]+/ /Test[0-9]+/i/Test[0 9] /i / Test[0-9]+/gi
99
Exercise Check for an input consisting of
numeric numbers only Code Code
Check for a required field Check for the following format:
2 digits – 2 digits – 4 digits2 digits 2 digits 4 digits
100
Summary HTML/XHTML: content Cascading Style Sheet (CSS): style and
layouty Script language: (JavaScript) control
HTML elementsH ML e ements Regular expression
101
jQjQuery
102
Introduction
jQuery: widely used JavaScript libraryjQ y y p y Purposes:
Separate JavaScript code (behaviour) from HTML p r J r p ( ur) fr m H MLdocuments (content)
Simplify task of writing JavaScript and in particular AJAX li tiAJAX applications
Reduce amount of data to be transferredS ll fil i i k l di Smaller file size quicker page loading
103
I d iIntroduction Example: $(“p”).hide();
Hide all <p> elementsp Features
HTML elements attributes and events HTML elements, attributes and events CSS style JavaScript effects and animationsJavaScript effects and animations AJAX applications Extensible through plug-insg p g Cross-browser support
104
Source Download jQuery
http://docs jquery com/Downloading jQuery http://docs.jquery.com/Downloading_jQuery <script src=“jquery-xxx.js”
type=“text/javascript”></script>yp j p p CDN (Content Delivery Network)
System of computers with copy of datay p py When client requests data, closest machine is used May have already cached jQuery filey y j y <script
src=“http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js” type="text/javascript"></script>
105
type= text/javascript ></script>
Basic Syntax $(selector).action()
$() jQ f ti $(): jQuery function selector: HTML element to “query” action: what kind of action to perform
$(selector) / jQuery(selector) $(selector) / jQuery(selector) Return all matched elements found in the
DOM DOM $ is a shorthand of jQuery
106
jQuery Selectors Element selectors
$(“h1”): Select all <h1> elements $( h1 ): Select all <h1> elements $(“h1 h2 p”): Select all <h1>, <h2> and <p>
elementselements $(“p.fname”): Select all <p> elements with
class=“fname”class= fname $(“#fname”): Select the element with
id=“fname”id= fname $(“div.nav.p”): Select all <p> elements inside
div with class “nav”107
div with class nav
jQuery Selectors Attribute selectors
$(“[href]”): Select all elements with the href attribute
$(“[name=‘fname’]”): Select all elements where the name attribute equals ‘fname’q
$(“[href != ‘#’]”): Select all elements with href attribute not equal to ‘#’
108
EEvents jQuery methods are called when an event is jQuery methods are called when an event is
triggeredBasic syntax: Basic syntax: $(selector).eventMethod(eventHandler(eventObj))
$( l ) M h d(f i ( Obj) { $(selector).eventMethod(function(eventObj) {// your code here
}) Examples:p
$(document).ready(function(){...}) $(document).click(function(){...})
109
$( ) (f (){ })
jQuery Document Ready $(document).ready(function())
Prevent jQuery code from running before the revent jQuery code from runn ng before the HTML document has been loaded
Examplep<script type=“text/javascript”> $(document).ready(function() { alert(“Displayed when page loaded”); });
/ i t<script type=“text/javascript”>
$(f () {</script> $(function() { alert(“Displayed when page loaded”); });shortcut version
110
});</script>
shortcut version
Click Event Method $(selector).click(): Execute the handler
function when the target element is clicked Example
A listener for the event “click” is event cl ck s added for each <p> after the document has been loaded
111
Other Event Methods
dblclick(): Target element is double-clicked() g m change(): Target element (form field) is
changed, .e.g. select menu has an option g , g pselected or text field/text area loses focus
blur(): Target field loses focus() g focus(): Target field is focused submit(): A form (<form> element) is submitted submit(): A form (<form> element) is submitted
112
Other Event Methods mouseenter(): Mouse pointer enters the
target elementtarget element mouseleave(): Mouse pointer leaves the
target elementtarget element mousedown(): Left mouse button is pressed
on the target elementon the target element mouseup(): Left mouse button is released
from the target elementfrom the target element
113
“on” Method for Event on(): Bind multiple events with
same/different handlerssame/different handlers Syntaxes
$(parent-element-to-monitor) on(“event1 event2 $(parent-element-to-monitor).on( event1 event2 ...”, “element-to-attach-event”, eventHandler());
$(parent-element-to-monitor).on({“event1”: $(p ) ({eventHandler1(), “event2”: eventHandler2(), ... }, “element-to-attach-event”);
li k() dbl li k() t () t click(), dblclick(), mouseenter() etc are shorthand of on().
114
Examples
115
“off” Method for Eventff() R th t( ) d/ off(): Remove the event(s) and/or
handler(s) bound to element(s) by using () h don() method
Syntaxy $(parent-element-to-monitor).off(“event”,
“element-from-detach-event”, ,eventHandler);
Example: Example $(document).off(“click”, “p”): Remove the
click event from all <p> elementsclick event from all p elements116
117
Traversing: Filtering $(selector).eq(i): Get the element at the index i, where the
elements are indexed with 0 refering to the first elementg $(selector).first(): Get the first element in the set of
elements$( l t ) l t() G t th l t l t i th t f $(selector).last(): Get the last element in the set of elements<body> <ul> <li> item 1 </li> <li> item 2 </li>
$(“li”).first()
$(“li”) eq(1) <li> item 3 </li> <li> item 4 </li> <li> item 5 </li>
$( li ).eq(1)
$(“li”).last()
118
</ul></body>
Traversing: Filtering$(selector) length: The property that contains number of $(selector).length: The property that contains number of elements
$(selector).each(fn): Execute the function fn for each selected element
Example:
119
Tree Traversal $(selector).parent(): Get the direct parent of the
element $(selector).prev(): Get the previous sibling of the
element $(selector).next(): Get the next sibling of the
element$( l ) h ld () G ll h d h ld $(selector).children(): Get all the direct children of the element$( l t ) fi d(d d t l t ) G t th $(selector).find(descendant-selector): Get the descendants of the element
120
Tree Traversal Example
<body> <div id="grandParent"> <div id="parent"> <div id="sister1"></div> <div id="me"> me
<div id "child1"> <div id= child1 > <div id="grandChild1"></div> </div> <div id="child2"> <div id="grandChild2"></div> <div id="grandChild3"></div> </div> </div> <div id="sister2"></div> <div id="brother1"></div>
</div>
121
</div> </div></body>
Tree Traversal<div id=“grandParent”>
$(“#me”).parent()
di id “ t”
d d “ ”
<div id=“brother1”>
<div id=“parent”>
$(“#me”).prev() <div id=“sister1”>
$(“# ”) t()<div id=“me”>
$(“#me”).children()
$(“#me”).next()
<div id=“sister2”>
<div id=“grandChild1”><div id=“grandChild3”>
<div id=“child1”>
<div id=“child2”>
descendantg<div id= grandChild3 >
$(“#me”).find(“#grandChild2”)<div id=“grandChild2”>
s
122
jQuery HTML Manipulation jQuery provides some methods to manipulate the
DOMDOM Basic syntax:
$(selector).manipulateMethod(newContent)$( ) p ( ) Methods
text(): Set or get text only content (innerText)h l() S i l di HTML (i HTML) html(): Set or get content including HTML (innerHTML)
val(): Set or get the value of the element width(): Set or get the width of the element (in pixels)w () g w f m ( p ) height(): Set or get the height of the element (in pixels)
123
jQuery HTML Manipulation Methods (contd)
addClass(class(es)-to-add): Add class(es) to the element Example
124
jQuery HTML Manipulation Other methods
$(selector).before(content-to-add): Add content before the selected element$( l t ) ft ( t t t dd) Add t t $(selector). after(content-to-add): Add content after the selected element
$(selector) attr(attribute newVal): Set or get $(selector). attr(attribute, newVal): Set or get values of HTML attributes
$(selector). prop(property, newVal): Set or get ( ) p p(p p y ) gvalues of properties of the element (e.g. tagName, nodeName, nodeType, checked, defaultChecked, selectedIndex defaultSelected)selectedIndex, defaultSelected)
125
“ ““prepend” and “append” prepend(): Add content to the beginning of the
content of the elementd() Add t t t th d f th t t append(): Add content to the end of the content
of the element
<h3 id=“result”> Your text: </h3>
126
/h3<span> ... </span>
“ ““prepend” and “append”
<h3 id=“result”> Your text: <span> ... </span> </h3>span ... /span /h3
127
Removal Methods remove(): Remove the element and its
contentcontent Syntax: $(target-element).remove(filter-
citeria);citeria); Example: $(“p”).remove(“.highlight”) removes
<p> elements of the class “highlight”p g gremoveClass(class(es)-to-remove): Remove specified class(es) from the elementspecified class(es) from the element
128
Removal methods
129
css Methodcss(): Set or get single or multiple style properties of the element
Syntaxes $(selector).css(“css-property”)
$(selector) css(“css property” “value”) $(selector).css( css-property , value ) $(selector).css({css-property1: “value1”, css-property2:
“value2”, ...}) Examples
var textColor = $(“p”).css(“color”); $(“h1”) css({“color”: “green” “background-color”: “yellow”}) $( h1 ).css({ color : green , background-color : yellow }) $(“h1”).css({color: “green”, backgroundColor: “yellow”})
130
EExercise Change the below document to use jQuery Change the below document to use jQuery
<html> <head> <script type="text/javascript">p yp /j p function emphasize(u) { u.style.backgroundColor = "yellow"; u.style.fontWeight = "bold"; u.style.fontWeight bold ; } </script> </head> </head> <body> <p onclick="emphasize(this)"> Text of paragraph 1 </p> <p onclick="emphasize(this)"> Text of paragraph 2 </p> <p onclick= emphasize(this) > Text of paragraph 2 </p> <p onclick="emphasize(this)"> Text of paragraph 3 </p> </body></html>
131
</html>
E iExercise Solution
ht lSolut on<html> <head> <script src="jquery.js"></script>
i " /j i " <script type="text/javascript"> $(document).ready( function() { $("p").click( function() { $(this).css( {"background-color": "yellow", "font-weight": "bold"} ); }); }); </script> </head> <body> <p> Text of paragraph 1 </p> <p> Text of paragraph 2 </p> <p> Text of paragraph 3 </p>
132
</body></html>
jQuery Effects jQuery includes some common effects such as
hiding sliding fadinghiding, sliding, fading. Other features include animations of CSS
ti s d st i d s tti sproperties and customized settings. hide() method
Syntax: $(selector).hide(v, fn) hide the element at speed v and then invoke
callback function fn v can be a descriptive string “slow”, “normal” or
“f t” l i illi d ( )“fast” or a value in milliseconds (ms)133
jQuery Effects $(selector).show(v, fn): show the element $(selector).toggle(v, fn): toggle between
hide() and show() $(selector).fadeIn(v, fn): fade in the
elemente ement $(selector).fadeout(v, fn): fade out the
elementelement $(selector).fadeToggle(v, fn): toggle
between fadeIn() and fadeOut()between fadeIn() and fadeOut()134
jQuery Effects $(selector).fadeTo(v, x, fn): fade the
l h ifi d i (0 1)element to the specified opacity x (0 – 1) $(selector).slideDown(v, fn): slide down the
element $(selector).slideUp(v, fn): slide up the $(se ector).s de p( , fn) s de up the
element $(selector) slideToggle(v fn): toggle $(selector).slideToggle(v, fn): toggle
between slideDown() and slideUp()
135
Examplep
136
“animate” method $(selector).animate({css properties}, v, fn)
A i t th l t b d th ifi d Animate the element based on the specified css properties
The element must have css property of position preset to p p y p pabsolute, relative or fixed when position is required to change.
Example: $(“#msg”) animate({“left”: “200px” Example: $( #msg”).animate({ left”: 200px”, “top”: “+=100px”, “opacity”: “0.4”}, 2000); Move the element with id “msg” to a position 200px from Move the element with id msg to a position 200px from
the left relative to the origin, 100px from top relative to its current vertical position and change its opacity to 0.4 within 2000 mswithin 2000 ms
137
Example
138
Chaining Chaining: Run several commands one after
the other in a single statement The same element is found only one time. Example: Example:
$(“div”).fadeOut(3000).fadeIn(1000)has the same effect as $(“div”).fadeOut(3000); $(“div”) fadeIn(1000);
139
$( div ).fadeIn(1000);140
C llb k F tiCallback Function
141
Callback Function Effect methods add a job to a (first-in-
first out) queue of the elementfirst-out) queue of the element. Animations perform one by one but not with
th ti sother actions. Callback allows execution of certain codes
f f or functions after an animation.
142