Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
20480A
Programming in HTML5 with JavaScript and
CSS3
MCT USE ONLY. STUDENT USE PROHIBITED
ii Course Title
Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
© 2012 Microsoft Corporation. All rights reserved.
Released: xx/20xx
MCT USE ONLY. STUDENT USE PROHIBITED
MICROSOFT LICENSE TERMS
OFFICIAL MICROSOFT LEARNING PRODUCTS
MICROSOFT OFFICIAL COURSE Pre-Release and Final Release Versions
These license terms are an agreement between Microsoft Corporation and you. Please read them. They apply to
the Licensed Content named above, which includes the media on which you received it, if any. These license
terms also apply to any updates, supplements, internet based services and support services for the Licensed
Content, unless other terms accompany those items. If so, those terms apply.
BY DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT
THEM, DO NOT DOWNLOAD OR USE THE LICENSED CONTENT.
If you comply with these license terms, you have the rights below.
1. DEFINITIONS.
a. “Authorized Learning Center” means a Microsoft Learning Competency Member, Microsoft IT Academy
Program Member, or such other entity as Microsoft may designate from time to time.
b. “Authorized Training Session” means the Microsoft-authorized instructor-led training class using only
MOC Courses that are conducted by a MCT at or through an Authorized Learning Center.
c. “Classroom Device” means one (1) dedicated, secure computer that you own or control that meets or
exceeds the hardware level specified for the particular MOC Course located at your training facilities or
primary business location.
d. “End User” means an individual who is (i) duly enrolled for an Authorized Training Session or Private
Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee.
e. “Licensed Content” means the MOC Course and any other content accompanying this agreement.
Licensed Content may include (i) Trainer Content, (ii) software, and (iii) associated media.
f. “Microsoft Certified Trainer” or “MCT” means an individual who is (i) engaged to teach a training session
to End Users on behalf of an Authorized Learning Center or MPN Member, (ii) currently certified as a
Microsoft Certified Trainer under the Microsoft Certification Program, and (iii) holds a Microsoft
Certification in the technology that is the subject of the training session.
g. “Microsoft IT Academy Member” means a current, active member of the Microsoft IT Academy
Program.
h. “Microsoft Learning Competency Member” means a Microsoft Partner Network Program Member in
good standing that currently holds the Learning Competency status.
i. “Microsoft Official Course” or “MOC Course” means the Official Microsoft Learning Product instructor-
led courseware that educates IT professionals or developers on Microsoft technologies.
MCT USE ONLY. STUDENT USE PROHIBITED
j. “Microsoft Partner Network Member” or “MPN Member” means a silver or gold-level Microsoft Partner
Network program member in good standing.
k. “Personal Device” means one (1) device, workstation or other digital electronic device that you
personally own or control that meets or exceeds the hardware level specified for the particular MOC
Course.
l. “Private Training Session” means the instructor-led training classes provided by MPN Members for
corporate customers to teach a predefined learning objective. These classes are not advertised or
promoted to the general public and class attendance is restricted to individuals employed by or
contracted by the corporate customer.
m. “Trainer Content” means the trainer version of the MOC Course and additional content designated
solely for trainers to use to teach a training session using a MOC Course. Trainer Content may include
Microsoft PowerPoint presentations, instructor notes, lab setup guide, demonstration guides, beta
feedback form and trainer preparation guide for the MOC Course. To clarify, Trainer Content does not
include virtual hard disks or virtual machines.
2. INSTALLATION AND USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is
licensed on a one copy per user basis, such that you must acquire a license for each individual that
accesses or uses the Licensed Content.
2.1 Below are four separate sets of installation and use rights. Only one set of rights apply to you.
ii. Use of Instructional Components in Trainer Content. You may customize, in accordance with the
most recent version of the MCT Agreement, those portions of the Trainer Content that are logically
associated with instruction of a training session. If you elect to exercise the foregoing rights, you
agree: (a) that any of these customizations will only be used for providing a training session, (b) any
customizations will comply with the terms and conditions for Modified Training Sessions and
Supplemental Materials in the most recent version of the MCT agreement and with this agreement.
For clarity, any use of “customize” refers only to changing the order of slides and content, and/or
not using all the slides or content, it does not mean changing or modifying any slide or content.
2.2 Separation of Components. The Licensed Content components are licensed as a single unit and you
may not separate the components and install them on different devices.
2.4 Third Party Programs. The Licensed Content may contain third party programs or services. These
license terms will apply to your use of those third party programs or services, unless other terms accompany
those programs and services.
2.5 Additional Terms. Some Licensed Content may contain components with additional terms,
conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also
apply to that respective component and supplements the terms described in this Agreement.
3. PRE-RELEASE VERSIONS. If the Licensed Content is a pre-release (“beta”) version, in addition to the other
provisions in this agreement, then these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not contain the
same information and/or work the way a final version of the Licensed Content will. We may change it
for the final version. We also may not release a final version. Microsoft is under no obligation to
provide you with any further content, including the final release version of the Licensed Content.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or
through its third party designee, you give to Microsoft without charge, the right to use, share and
commercialize your feedback in any way and for any purpose. You also give to third parties, without
charge, any patent rights needed for their products, technologies and services to use or interface with
any specific parts of a Microsoft software, Microsoft product, or service that includes the feedback. You
will not give feedback that is subject to a license that requires Microsoft to license its software,
technologies, or products to third parties because we include your feedback in them. These rights
MCT USE ONLY. STUDENT USE PROHIBITED
survive this agreement.
c. Term. If you are an Authorized Training Center, MCT or MPN, you agree to cease using all copies of the
beta version of the Licensed Content upon (i) the date which Microsoft informs you is the end date for
using the beta version, or (ii) sixty (60) days after the commercial release of the Licensed Content,
whichever is earliest (“beta term”). Upon expiration or termination of the beta term, you will
irretrievably delete and destroy all copies of same in the possession or under your control.
4. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed Content,
which may change or be canceled at any time.
a. Consent for Internet-Based Services. The Licensed Content may connect to computer systems over an
Internet-based wireless network. In some cases, you will not receive a separate notice when they
connect. Using the Licensed Content operates as your consent to the transmission of standard device
information (including but not limited to technical information about your device, system and
application software, and peripherals) for internet-based services.
b. Misuse of Internet-based Services. You may not use any Internet-based service in any way that could
harm it or impair anyone else’s use of it. You may not use the service to try to gain unauthorized access
to any service, data, account or network by any means.
5. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some rights
to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more
rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that only
allows you to use it in certain ways. Except as expressly permitted in this agreement, you may not:
• install more copies of the Licensed Content on devices than the number of licenses you acquired;
• allow more individuals to access the Licensed Content than the number of licenses you acquired;
• publicly display, or make the Licensed Content available for others to access or use;
• install, sell, publish, transmit, encumber, pledge, lend, copy, adapt, link to, post, rent, lease or lend,
make available or distribute the Licensed Content to any third party, except as expressly permitted
by this Agreement.
• reverse engineer, decompile, remove or otherwise thwart any protections or disassemble the
Licensed Content except and only to the extent that applicable law expressly permits, despite this
limitation;
• access or use any Licensed Content for which you are not providing a training session to End Users
using the Licensed Content;
• access or use any Licensed Content that you have not been authorized by Microsoft to access and
use; or
• transfer the Licensed Content, in whole or in part, or assign this agreement to any third party.
6. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to you in
this agreement. The Licensed Content is protected by copyright and other intellectual property laws and
treaties. Microsoft or its suppliers own the title, copyright, and other intellectual property rights in the
Licensed Content. You may not remove or obscure any copyright, trademark or patent notices that
appear on the Licensed Content or any components thereof, as delivered to you.
MCT USE ONLY. STUDENT USE PROHIBITED
7. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations. You
must comply with all domestic and international export laws and regulations that apply to the Licensed
Content. These laws include restrictions on destinations, End Users and end use. For additional
information, see www.microsoft.com/exporting.
8. LIMITATIONS ON SALE, RENTAL, ETC. AND CERTAIN ASSIGNMENTS. You may not sell, rent, lease, lend or
sublicense the Licensed Content or any portion thereof, or transfer or assign this agreement.
9. SUPPORT SERVICES. Because the Licensed Content is “as is”, we may not provide support services for it.
10. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail
to comply with the terms and conditions of this agreement. Upon any termination of this agreement, you
agree to immediately stop all use of and to irretrievable delete and destroy all copies of the Licensed
Content in your possession or under your control.
11. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed Content.
The third party sites are not under the control of Microsoft, and Microsoft is not responsible for the
contents of any third party sites, any links contained in third party sites, or any changes or updates to third
party sites. Microsoft is not responsible for webcasting or any other form of transmission received from
any third party sites. Microsoft is providing these links to third party sites to you only as a convenience,
and the inclusion of any link does not imply an endorsement by Microsoft of the third party site.
12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates and support services are
the entire agreement for the Licensed Content.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws of that
country apply.
14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of
your country. You may also have rights with respect to the party from whom you acquired the Licensed
Content. This agreement does not change your rights under the laws of your country if the laws of your
country do not permit it to do so.
15. DISCLAIMER OF WARRANTY. THE LICENSED CONTENT IS LICENSED "AS-IS," "WITH ALL FAULTS," AND "AS
AVAILABLE." YOU BEAR THE RISK OF USING IT. MICROSOFT CORPORATION AND ITS RESPECTIVE
AFFILIATES GIVE NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS UNDER OR IN RELATION TO
THE LICENSED CONTENT. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS
WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS,
MICROSOFT CORPORATION AND ITS RESPECTIVE AFFILIATES EXCLUDE ANY IMPLIED WARRANTIES OR
CONDITIONS, INCLUDING THOSE OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NON-INFRINGEMENT.
MCT USE ONLY. STUDENT USE PROHIBITED
16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. TO THE EXTENT NOT PROHIBITED BY
LAW, YOU CAN RECOVER FROM MICROSOFT CORPORATION AND ITS SUPPLIERS ONLY DIRECT
DAMAGES UP TO USD$5.00. YOU AGREE NOT TO SEEK TO RECOVER ANY OTHER DAMAGES, INCLUDING
CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES FROM MICROSOFT
CORPORATION AND ITS RESPECTIVE SUPPLIERS.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this agreement
are provided below in French.
Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses dans ce
contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute
utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie
expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage.
Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects,
accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera
pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus
par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays
si celles-ci ne le permettent pas.
Acknowledgments
Microsoft Learning wants to acknowledge and thank the following for their contribution toward
developing this title. Their effort at various stages in the development has ensured that you have a good
classroom experience.
His current focus is on building rich interactive web applications using ASP.NET, HTML5 and JavaScript.
He is an active member of the developer community and the creator of a number of popular open source
projects.
Andy is a regular speaker at conferences and spends most his spare time developing .NET solutions for
large companies based in the UK, Europe, and Asia.
He has authored a number of development books as well as over 20 Microsoft Learning courses..
MCT USE ONLY. STUDENT USE PROHIBITED
Course Title xiii
Contents
Module 1: Overview of HTML and CSS
Lesson 1: Overview of HTML page 3
Lesson 2: Overview of CSS page 22
Lesson 3: Creating a Web Application by Using Visual Studio 2012 page 31
Lab: Exploring the Contoso Conference Application page 39
Course Description
Note: This first release (‘A’) MOC version of course 20480A has been developed on RTM software.
Microsoft Learning will release a ‘B’ version of this course with enhanced PowerPoint slides, copy-
edited content, and Course Companion content on Microsoft Learning site.
This course provides an introduction to HTML5, CSS3, and JavaScript. IT helps students gain basic
HTML5/CSS3/JavaScript programming skills. Students will learn how to use HTML5, CSS3, and JavaScript
to build responsive and scalable Web applications that can dynamically detect and adapt to different form
factors and device capabilities.
Audience
This course is intended for professional developers who have 6-12 months of programming experience
and who are interested in developing applications using HTML5 with JavaScript and CSS3 (either Windows
Store apps for Windows 8 or web applications).
This course is intended for students who have the following experience:
• 1 – 3 months experience creating Web applications
Student Prerequisites
Before attending this course, students must have at least three months professional development
experience.
In addition to their professional experience, students who attend this training should have a combination
of practical and conceptual knowledge related to HTML5 programming. This includes the following
prerequisites:
Course Objectives
After completing this course, students will be able to:
• Explain how to use Visual Studio 2012 to create and run a Web application.
• Describe the new features of HTML5, and create and style HTML5 pages.
• Send and receive data to and from a remote data source by using XMLHTTPRequest objects and
jQuery AJAX operations.
• Create HTML5 Web pages that can adapt to different devices and form factors.
• Add advanced graphics to an HTML5 page by using Canvas elements, and by using and Scalable
Vector Graphics.
Course Outline
The course outline is as follows:
Course Materials
The following materials are included with your kit:
• Course Handbook: a succinct classroom learning guide that provides the critical technical
information in a crisp, tightly-focused format, which is essential for an effective in-class learning
experience.
• Lessons: guide you through the learning objectives and provide the key points that are critical to
the success of the in-class learning experience.
• Labs: provide a real-world, hands-on platform for you to apply the knowledge and skills learned
in the module.
• Module Reviews and Takeaways: provide on-the-job reference material to boost knowledge
and skills retention.
• Modules: include companion content, such as questions and answers, detailed demo steps and
additional reading links, for each lesson. Additionally, they include Lab Review questions and
answers and Module Reviews and Takeaways sections, which contain the review questions and
answers, best practices, common issues and troubleshooting tips with answers, and real-world
issues and scenarios with answers.
• Resources: include well-categorized additional resources that give you immediate access to the
most current premium content on TechNet, MSDN®, or Microsoft® Press®.
Note: For this version of the Courseware on Prerelease Software, Companion Content is not
available. However, the Companion Content will be published when the next (B) version of this
course is released, and students who have taken this course will be able to download the
Companion Content at that time from the
http://www.microsoft.com/learning/companionmoc site. Please check with your instructor
when the ‘B’ version of this course is scheduled to release to learn when you can access
Companion Content for this course.
Student Course files: includes the Allfiles.exe, a self-extracting executable file that contains all
required files for the labs and demonstrations.
Note: For this version of the Courseware on Prerelease Software, Allfiles.exe file is not available.
However, this file will be published when the next (B) version of this course is released, and students
who have taken this course will be able to download the Allfiles.exe at that time from the
http://www.microsoft.com/learning/companionmoc site.
• Course evaluation: at the end of the course, you will have the opportunity to complete an online
evaluation to provide feedback on the course, training facility, and instructor.
MCT USE ONLY. STUDENT USE PROHIBITED
iv About This Course
Important: At the end of each lab, you must close the virtual machine and must not save
any changes. To close a virtual machine (VM) without saving the changes, perform the
following steps:
2. In the Close dialog box, in the What do you want the virtual machine to do? list, click
Turn off and delete changes, and then click OK.
The following table shows the role of each virtual machine that is used in this course:
Software Configuration
The following software is installed on each VM:
• Microsoft Windows 8 Enterprise
Course Files
The files associated with the labs in this course are located in the E:\Labfiles folder on each virtual
machine.
Classroom Setup
Each classroom computer will have the same virtual machines configured in the same way.
Hardware Level 6+
Module 1
Overview of HTML and CSS
Contents:
Module Overview 1-2
Modu
ule Ove
erview
Ob
bjectives
e, you will be able to:
Aftter completing this module
• Explain how
w to use CSS tto apply basic styling to a w
web page
• Describe the tools that M
Microsoft® Vissual Studio® provides for building
b web applications
Programming in HTML5 with JavaScrript and CSS3 1-3
3
Lesson 1
Overrview of HTMLL
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Create an
n HTML form page.
• Integrate JavaScript co
ode into an HT
TML page.
1-4 Overview
w of HTML and CSS
Th
he Structu
ure of an H
HTML Pag
ge
HT TML is an acro onym for Hypper Text Markkup Language e. It is a static language thatt determines the
strructure and se emantic mean ning of a web page. You use e HTML to cre eate content and
a metadataa that
bro owsers use to render and d display inform
mation. HTML ccontent can in mages, audio, video,
nclude text, im
forrms, lists, tables, and many other items. A
An HTML pag ge can also co ontain hyperlinnks, which con
nnect
pages to each o other and to w
web sites and resources else
ewhere on the e Internet.
Th
he minimum maintainable
e page
<
<!DOCTYPE htm
ml>
<
<html lang=”e
en”>
<head>
<meta cha
arset=utf-8 />
<title>Th
he Smallest Page</title
e>
</head>
<body>
</body>
<
</html>
<
<!DOCTYPE html>
Programming in HTML5 with JavaScript and CSS3 1-5
You should write all your new web pages by using HTML5, but you are likely to see many web pages
written by using HTML 4.01 or earlier. Pages that are not based on HTML5 commonly use one of the
following classes of DOCTYPE:
• Transitional DOCTYPEs, which allow the use of deprecated, presentation-related elements from
previous versions of HTML.
• Frameset DOCTYPEs, which allow the use of frames in addition to the elements allowed by the
transitional DOCTYPE.
• Strict DOCTYPEs, which do not permit the use of frames or deprecated elements from previous
versions of HTML.
At all times, if you cannot use the HTML5 DOCTYPE you should use the strict HTML 4.01 DOCTYPE. If an
HTML file has no DOCTYPE, browsers may use their own value and might render your web page
inconsistently, so it is important to include the DOCTYPE.
1-6 Overview
w of HTML and CSS
Taags, Eleme
ents, Attributes, and
d Contentt
The head and b body of a web page both usse HTML elem ments to defin
ne its structure
e and contentts. For
exaample, a paraagraph elemen
nt, representin
ng a paragrap
ph of text on the
t page, con nsists of:
• An opening
g tag, <p>, to
o denote the sstart of the paaragraph
• Text conten
nt
Neest elements w
within each otther to elicit m
more semanticc information about the co ontent it contaains. If it is
no
ot obvious from
m the contextt, indent neste ed elements tto help keep ttrack of which
h are parent annd which
are
e child elemen
nts.
Th
he body of a simple docum
ment
<
<body>
<h1 class=”blue”>An in
ntroduction to elements, tags and c
contents</h1
1>
<p>
<strong>E
Elements</st
trong> consist of <stron
ng>content</
/strong> boo
okended by a
<em>start
t</em> tag a
and an <em>e
end</em> tag.
</p>
<hr />
<p>
Certain e
elements, su
uch as the h
horizontal ru
ule element,
, do not nee
ed content ho
owever
a
and use a
single, s
self-closing
g tag. These
e are known a
as empty ele
ements.
</p>
<
</body>
Each HTML elem ment tells the browser something about the informatiion that sits bbetween its op pening and
clo
osing tags. For example, thee strong and em elementss represent “sttrong importa ance” and “em mphasis” for
the
eir contents, w
which browsers tend to rennder respectively as text in bold
b and text in italics. h1 elements
rep
present a top--level headingg in your docu
ument, which browsers ten nd to render as text in a largge, bold
fon
nt.
Programming in HTML5 with JavaScript and CSS3 1-7
Attributes provide additional information, presentational or semantic, about the contents of an element.
They appear within the start tag of an element and have a name and a value. The name should be in
lowercase characters. Most values are pre-defined based on the attribute they are for, and should be
contained within quotes. In the previous example, the h1 start tag contains the class attribute set to the
value blue.
Most attributes can qualify only certain elements. However, HTML defines a group of global attributes for
use with any element.
Additional Reading: You can view a complete list HTML global attributes on the W3C web
site, at http://go.microsoft.com/fwlink/?LinkID=267708.
1-8 Overview
w of HTML and CSS
Displaying Text in HT
TML
He
eadings and Paragrap
phs
HT
TML has includ
ded elementss to identify paaragraphs and
d headings in a document since v1 in 19
992.
Ma
arking up tex
xt
<
<body>
<h1>An Introduction to
o HTML</h1>
<p>In this module, we look at thee history of HTML and CS
SS.</p>
<h2>In the Beginning</
/h2>
<p>
WorldWide
eWeb was a p
piece of sofftware writte
en by Sir Ti
im Berners-L
Lee at CERN a
as a
r
replacement f
for
Gopher. I
It and HTML v1 were madde open sourc
ce software in 1993. Th
he World Wide
e Web as
w
we know it
started w
with this pi
iece of softtware.
</p>
<h3>Browser Wars</h3>
<p>The open
nness of Wor
rldWideWeb mmeant many di
ifferent web
b browsers w
were created early
o
on, including
g Netscape N
Navigator annd NCSA Mosai
ic, which la
ater became Internet
E
Explorer.</p>
>
<
</body>
Whhen writing HHTML markup,, remember th hat any seque ence of whitesspace characte ers – spaces, ttabs, and
carriage returnss – inside text are treated ass a single spacce. The only exception
e to this is when th
hat
seq
quence is insidde a <pre> e element, in wh hich case the browser
b displaays all the spaaces.
Programming in HTML5 with JavaScript and CSS3 1-9
Emphasis
HTML defines four elements that denote a change in emphasis in the text they surround from the text in
which they are nested:
• <strong> identifies text that is more important than its surrounding text. The browser usually renders
this content in bold.
• <em> identifies text that needs to be stressed. The browser usually renders this content in italics.
You can combine and nest the <strong>, <em>, <b>, and <i> elements to indicate different types of
emphasis.
Note: The <b> and <i> elements in HTML4 are simply instructions for displaying the text,
rather than specifying than some semantic meaning. In HTML5, it is better to use <strong> and
<em> rather than <b> and <i>.
Lists
Lists organize sets of information in a clear and easily understood format. HTML defines three types of list:
• Unordered lists group sets of items in no particular order
• Definition lists group sets of name-value pairs, such as terms and their definitions
All three list types use a tag to define the start and end of the list - <ul>, <ol>, and <dl> respectively.
Individual list entries are identified with the <li> tag for unordered and ordered lists, while definition lists
use two tags per list item; <dt> for the name, or term, and <dd> for its value, or definition.
HTML provides for listing set of things, steps, and name-value pairs.
<dd>Originator of Linux</dd>
<dt>Charles Herzfeld</dt>
<dd>Authorized the creation of ARPANET, the predecessor of the Internet</dd>
</dl>
</body>
You can also include another list within a list item, as long as the nested list relates to that one specific
item. The nested list does not have to be the same type of list as its parent, although context dictates that
this is usually the case.
You may write a table of contents as an ordered list of chapter names. Each list item may then include a
nested list of headings within that chapter.
Browsers usually render nested lists by indenting them further into the page, and additionally changing
the bullet point style for unordered lists or restarting the list numbering for ordered lists.
Programming in HTTML5 with JavaScrippt and CSS3 1-11
1
D
Displaying
g Images and Linking Docum
ments in H
HTML
O
Only the src aattribute is maandatory.
O of the mo
One ore common types of imag
ge to include in a web page
e is a logo of some kind, likke this:
A
Adding an im
mage to a we
eb page
<body>
<p>
<img sr
rc=”logo.jpg
g” alt=”My Web site logo
o” height=”1
100” width=”100” />
</p>
<h1>Welco
ome to my site!</h1>
</body>
should be displayed at which resolution. The W3C Responsive Images Community Group
http://www.w3.org/community/respimg/ is hoping to figure out this problem soon.
Hypertext Links
The main reason for the invention of HTML was to link documents together. The <a> tag, also known as
the anchor tag, allows you to identify a section of content in your web page to link to another resource on
the web. Typically the target of this hypertext link is another web page, but it could equally be a text file,
image, archive file, email, or web service. When you view your web page in a browser, you click the
content surrounded by the anchor tags to have the linked document downloaded by the browser.
• The target attribute identifies where the browser will display the linked page; valid values are _blank,
_parent, _self, and _top
• The rel attribute identifies what kind of link is being created
• The type attribute identifies the MIME type of the linked resource
One common use for hypertext links is to build a navigation menu on a page so the user can visit other
pages in the site.
The href attribute is the most important part of linking one online resource to another. You can use
several different value types:
G
Gathering
g User Inp
put by Usin
ng Forms in HTML
• The meth
hod attribute,, which define
es how the data is sent to th
he server. Valid values are:
o GET for HTTP GET
T. This is the default value, b
but is not secu
ure
o POST
T for HTTP PO
OST. This is the
e preferred vaalue
F
Form Contrrols
An <input> e
A element repre esents the main HTML dataa entry control and has man ny different fo
orms based
o its type attribute, as sho
on own in the folllowing table. In addition, tthe value attribute sets a default value
f numeric or
for o text-based ccontrols, and the name attrribute to iden ntify the name e of the controol.
Value Resu
ult
Value Result
replaced by asterisks.
reset A reset button. Clicking this resets all the fields to their initial
values.
submit A submit button. Clicking this will submit the current form
values to the action page for processing.
image An image for use as a submit button. Use the src attribute to
identify the image to be used.
There are four other HTML elements that you can use in a form:
• <textarea>, which generates a free-form, multiline, plain text edit box; use the rows and cols
attributes to set its size.
• <select>, which defines a list box or drop-down list. Use the multiple attribute to indicate if the user
can select more than one item from the list and <option> elements nested within <select> to
identify the items. Use the <option>’s selected attribute to indicate that it is selected by default and
its value attribute to indicate a value other than its text content to be sent to the server when the
form is submitted.
• <button>, which defines a button. Use the type attribute to indicate whether it is a submit, reset, or
button (does nothing) button. The default is submit.
You should use the <button> element rather than its <input> equivalent if you need the content
displayed by the button to be more complex than a simple piece of text or a single picture.
• <fieldset>, which identifies a group of controls in a form. The browser reflects this by drawing a box
around the contents of the <fieldset> and labeling the box with a name. This name is set by using
the <legend> element, which must be the first child of the <fieldset> element.
• <label>, which identifies a text label associated with a form control. It does so either by surrounding
both the text and the control, or by surrounding the text and setting its for attribute to the id of the
form control.
You can use a form to gather many types of input from the user:
Programming in HTML5 with JavaScript and CSS3 1-15
Demonstration: Crea
ating a Sim
mple Contact Form
m
In this demonstration, you wiill see how to build a simple contact form
m that enable
es a user to se
end a
meessage to the organization running a we eb site.
De
emonstration Steps
Cre
eate an HTMLL Page
1. On the Win
ndows 8 Start screen, right--click outside of any tile, an
nd in the task bar click All a
apps.
2. On the Win
ndows 8 Start screen, in the
e Windows A
Accessories se
ection, click N
Notepad.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-
-8" />
<title>C
Contact Us</
/title>
</head>
<body>
</body>
</html>
Ad
dd Content to the Page
<h1>Contact Contoso C
Conferencing
g</h1>
<p>Contoso
o Conferenci
ing Ltd.</p>
>
<p>123 South Street<b
br />
Somewhere<
<br />
Over There<br />
<em>USA</em></p>
Programming in HTML5 with JavaScript and CSS3 1-17
3. Add a hyperlink for the company's contact email address. Note the use of the mailto: protocol rather
than the more common http://.
<p>
<a href="mailto:contact@contoso.com">
contact@contoso.com</a>
</p>
4. Add the following text to invite users to use the contact form.
<p>
If you would like to contact Contoso Conferencing, whether you're interested in our
services or in a conference we're currently organizing, don't hesitate to contact us
using our enquiry form (<strong>Bold fields</strong> are required).
</p>
1. Add the following <form> element to the page beneath the text created previously.
2. Add the following <fieldset> element and submit button to the form (between the <form …> and
</form> tags).
<fieldset>
<legend>
Your Details and Enquiry
</legend>
</fieldset>
<input type="submit" value="Send" />
3. Add the unordered list shown in the following code sample to the <fieldset> element below the
</legend> tag. This list contains input elements for the user's name, telephone number, email
address, and a message.
<ol>
<li>
<label>
<strong>Name</strong><br />
<input type="text"
name="UserName" />
</label>
</li>
<li>
<label>
Telephone<br />
<input type="text"
name="Phone" />
</label>
</li>
<li>
<label>
Email Address<br />
<input type="text"
name="Email" />
</label>
</li>
<li>
<label>
<strong>Message</strong><br />
1-18 Overview of HTML and CSSS
<tex
xtarea name=
="Message"
co
ols="30" row
ws="10">Add your message here
</textarea>
</label>
</li>
</ol>
ew the Page
Vie
Atttaching Scripts
S to an HTML Page
HTTML enables yyou to define the layout forr your web pa ages, but aparrt from the <fform> element it does
no
ot provide for any interactio on with the usser. Additionaally, the layoutt defined by using
u HTML markup
m
ten
nds to be fairlly static. You ccan add dynamic behavior to a page by writing JavaSScript code.
There are severaal ways that yyou can includ
de JavaScript in your web page, all involvving the <scriipt>
ele
ement:
<script t
type="text/javascript">
alert('
'I am a line
e of JavaScript');
</script>
>
<script t
type="text/javascript" src="alertme
e.js"></script>
<script t
type="text/javascript"
src="ht
ttp://ajax.c
contoso.com/ajax/jQuery/
/jquery-1.7.2.js">
</script>
>
Alw
ways specify b
both start and
d end <script> tags, even iif you are linkking to an exte
ernal script file
e and you
have no content between the e tags.
Programming in HTML5 with JavaScript and CSS3 1-21
It is common for a web application to divide JavaScript functionality into several scripts. Additionally,
many web applications use third party JavaScript files (such as those that implement jQuery). The order in
which you add links to JavaScript files is important, and to ensure that they are in scope you must add
links to scripts that define objects and functions before the scripts that use these objects and functions.
Older browsers do not always support JavaScript, and sometimes users running more modern browsers
may disable JavaScript functionality for security reasons. In these cases, any features on your web pages
that use JavaScript may not run correctly. You can alert the user that this is the case by using the
<noscript> element. This element enables a browser to display a message, warning the user that the
page may not operate correctly unless JavaScript is enabled.
Use the <noscript> element to alert users that your page uses JavaScript, and so the user should enable
JavaScript in the browser in order to display your page correctly.
Best Practice: In general, it is good practice to add links to scripts as the last elements
nested inside the <body> element. Also, remember that the order of the scripts is important, so
add links for dependent scripts after those on which they depend.
1-22 Overview of HTML and CSSS
Lesson 2
Overv
view of CSS
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
• ow CSS selecto
Describe ho ors work
• Describe ho
ow CSS styles inherit and caascade
O
Overview of CSS Sy
yntax
CSS is an acro
C onym for Casccading Style Sheets. CSS pro ovides the standard way off defining how w a browser
s
should displayy the contentss of a web page. CSS enablles you to attaach presentation rules to frragments of
H
HTML based oon selectors thhat target HTML elements by name, id, o or class. It also
o enables you
u to vary how
a page is pressented accordding to the forrm factor of th
he device on w which it is displayed, from a large
m
monitor to a smartphone,
s aand even on aan audio readder or printer.
E
Every CSS rule
e has the same basic structu
ure:
selector {
property11:value;
property22:value;
..
propertyNN:value;
}
• Every <h1> element should have text that is 42px high, pink and in Segoe UI font
• Every <em> element should have a yellow background color and its text in italics
When writing CSS, note that any sequence of whitespace characters is treated as a single space character.
Programming in HTTML5 with JavaScrippt and CSS3 1-25
5
H
How CSS Selectors Work
• The elem ment selectorr identifies thee group of all elements in the page with that name. Fo
or example,
h2 {} returns the set of all level two headings in th
he page.
I
Introducing tthe element,, class and id selectors
h2 {
font-size
e: 24px;
}
.red {
color: re
ed;
}
#alert {
backgroun
nd-color: re
ed;
color: wh
hite;
1-26 Overview of HTML and CSS
You can combine selectors by using concatenation. In the following example, the two rules combine
selectors to identify a more specific set of elements than either does on its own.
The selector, h2.blue returns the set of <h2> elements with the class "blue", and h2#toc returns the set of
<h2> elements with id "toc".
Combining selectors
h2.blue {
color: blue;
}
h2#toc {
font-weight: bold;
}
Note that these two sets may intersect, in which case the CSS properties and values for both rules will
apply—in this case to the set of <h2> elements with id "toc" and class "blue".
The following table shows examples of the various ways you can concatenate selectors and the set of
elements that the browser returns:
section h2 Returns any <h2> elements nested within a <section> element at any level.
section > h2 Returns any <h2> elements nested immediately under a <section> element
section + h2 Returns any <h2> elements immediately following and sharing the same
parent element as a <section> element
section ~ h2 Returns any <h2> elements following and sharing the same parent element
as a <section> element
Returns any <input> elements that use the type attribute, whatever
input[type]
its value.
input[type="text"] Returns any <input> elements where the type attribute value is exactly
equal to the string "text".
input[foo~="red"] Returns any <input> elements where the foo attribute (for instance, the
class attribute) contains a space-separated list of values, one of which is
exactly equal to "red".
input[type^="sub"] Returns any <input> elements where the type attribute value begins
exactly with the string "sub".
input[type$="mit"] Returns any <input> elements where the type attribute value ends
exactly with the string "mit".
input[type*="ubmi"] Returns any <input> elements where the type attribute value contains
the substring "ubmi".
input[foo|="en"] Returns any <input> elements where the foo attribute value is either
exactly "en" or begins exactly with "en-", i.e. the value plus a hyphen.
You can combine attribute selectors by concatenating them. For example, to return a set of all checkboxes
that are checked by default, you would use the following selector:
input[type="checkbox"][selected] {}
1-28 Overview of HTML and CSSS
As the phrase Cascading Style e Sheets sugg gests, elementts on a page ccan be subjectted to several cascading
tra
ansformationss depending o on relationship ps among the e elements and
d the style she
eets associate
ed with a
o understand two conceptss: inheritance between
page. To create successful styyle sheets, it iss important to
HTTML elementss, and how mu ultiple CSS rules cascade as they are app plied to HTML elements.
HT
TML Inheritance
In a web page, HTML
H elemen nts inherit som arent elements unless specified
me properties from their pa
oth
herwise. This iis of great imp
portance; with nce, you would have to decclare several rules for
hout inheritan
eveery single elem
ment on a page.
Co
onsider the sceenario in whicch you want aall text on a web page to usse the Candarra font. You caan set the
<b
body> elemen nt of your pagge to use this font, and inheeritance mean
ns that text in every other e
element
ne
ested inside th
he body will allso use Candaara unless anoother, more sp
pecific rule sup
pplants it.
body {
b
font-family: Candara;
}
Note: Nott all CSS propperties are inhe erited from parent to child, because it w
would make no o
sen
nse to do so. For example, if you set a baackground im mage for an <a article> elemeent, it would
pro
obably not be me background
e useful for alll the child secctions and parragraphs to diisplay the sam
image.
Programming in HTML5 with JavaScript and CSS3 1-29
Cascading Rules
A single element in an HTML page may be matched against more than one selector in a style sheet and
be subjected to several different styling rules. The order in which these rules are applied could cause the
element to be rendered in different ways. The cascade mechanism is the way in which style rules are
derived and applied when multiple, conflicting rules apply to the same element; it ensures that all
browsers display the element in the same way.
There are three factors that browsers must take into consideration when they apply styling rules:
1. Importance. You can ensure a certain property is always applied to a set of elements by appending
the rule with !important.
2. Specificity. Style rules with the least specific selector are applied first, then those for the next specific,
and so on until the style rules for the most specific selector are applied.
3. Source order. If styles rules exist for selectors of equal specificity, they are applied in the order given
in the style sheet.
Reference Links: For more information on inheritance and the cascade, including details
on how the specificity of a selector is calculated, go to
http://go.microsoft.com/fwlink/?LinkID=267710
1-30 Overview of HTML and CSSS
Ad
dding Sty
yles to An HTML Pag
ge
HT
TML enables yyou to attach your CSS rule
es to your web
b page in thre
ee ways. You ccan:
<p style=
="font-family : Candara; font-size:
: 12px; "> … </p>
<style tyype="text/cs
ss">
p {
font--family : Ca
andara; font-size: 12px;
;
}
</style>
• Write all yo
our rules in a sseparate style sheet file with .css extensio
on and then reference it in the
<head> ele ement of the p page by using g a <link> tagg.
<link rel
l="style she
eet" type="text/css" hre
ef="mystyles
s.css" media=
="screen">
• The type atttribute indicaates the MIMEE type of the d d; the correctt type for
document being referenced
style sheetss is text/css which
w is also th ue for this atttribute
he default valu
Lesson 3
Creatting a W
Web Ap
pplicatiion by Using V
Visual S
Studio 2012
2
Visual Studio 2012 offers a comprehensiive set of tools for developing web appliications. From
V m HTML
f
formatting to JavaScript de evelopers using the
ebugging, it iss a must-use ttool for web aapplication de
W
Windows plattform. Interne
et Explorer 10 also contains a number of useful tools ffor inspecting a web page
a the style sheets and scripts it referen
and nces.
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain ho
ow to use the
e F12 Develop nternet Explorer
per Tools for In
1-32 Overview of HTML and CSSS
Developing
g Web Applicationss by Using
g Visual Sttudio 2012
2
Vissual Studio 20
012 is the currrent version o
of Microsoft's primary suite of tools for developers. Wiith Visual
Stu
udio 2012, you can perform m the followin ng tasks:
• Debug web
b applications..
Vissual Studio 20
012 provides e bugging features for JavaScript code. You
extensive deb u can set brea akpoints,
sin
ngle step through code, exaamine and mo odify the conttents of variab
bles, view the call stack, and
d perform
maany other com mmon debugg ging tasks.
• Deploy web
b applicationss to a web servver, or to the cloud with W
Windows Azure
e.
Vissual Studio 20
012 provides tthe Publish W hich enables yyou to quicklyy deploy a web
Web wizard, wh
ap n deploy a web
pplication to a web server. If you have the Windows Azzure SDK instaalled, you can
pplication directly to the clo
ap oud.
There are severaal editions of Visual Studio.. At one end oof the scale, V
Visual Studio Express
E 2012 ffor Web is
fre
ee to downloa ad and install. It targets hob
bbyists. At the
e other end, VVisual Studio Ultimate
U 2012
2 is aimed at
larrge teams of d
developers bu uilding and maaintaining entterprise-level applications. All of them have the
samme core level of support foor developing web applications. This includes:
Vissual Studio alsso includes a new developm ment web servver called IIS Express. This web
w server prrovides
maany of the sam hat it is optimized for the d
me features ass IIS, except th development environment.
e
Programming in HTML5 with JavaScript and CSS3 1-33
Note: Previous editions of Visual Studio provided the ASP.NET Development Server. This
server is still available, but IIS Express has fewer limitations. For example, IIS Express includes the
integrated pipeline mode of the full IIS that was not available in the ASP.NET Development
Server.
Additional Reading: For detailed information about the new features of Visual Studio
2012, visit the Visual Studio 2012 site at http://go.microsoft.com/fwlink/?LinkID=267711.
1-34 Overview of HTML and CSSS
Demonstration: Crea
ating a Web
W Appliccation by Using Visu
ual Studio
o 2012
Vissual Studio 20
012 is the currrent version o
of Microsoft's iintegrated de
evelopment en nvironment (IDE). This
de
emonstration shows
s the primary featuress that Visual Studio provide g web applications.
es for building
De
emonstration Steps
Cre
eate a Web Siite Project
1. On the Win udio 2012 tile.
ndows 8 Start screen, click the Visual Stu
2. In Visual Stu
udio, on the F
File menu, point to New, and then click Web Site.
Note: It d
does not matteer whether yo
ou select the V or Visual C# ttemplates in the
Visual Basic o
lefft pane; the te
emplates for b
both language es enable you to create HTM
ML5 web pag ges and
implement funcctionality by u using JavaScrip
pt.
4. From the w
web location drop down listt, click File Sysstem, set the file path to
E:\Democoode\DemoWe ebSite, and th
hen click OK.
1. In Visual Stu
udio, click Sollution Explorrer.
5. In the Solution Explorer window, right-click ContactUs.html, and then click Set As Start Page.
6. In the Solution Explorer window, right-click the DemoWebSite project, point to Add, and then click
New Folder
8. Right-click the styles folder, point to Add, and then click Add New Item
9. In the Add New Item - DemoWebSite dialog box, in the middle pane, click Style Sheet, in the
Name box, type ContactUsStyles.css, and then click Add.
Note: You can also use the Add New Item dialog box to create new JavaScript and HTML
files and add them to a project.
10. In the ContactUsStyles.css file, add the following style shown in bold:
body {
font-family: 'Times New Roman';
color: blue;
}
Note: Notice that the new CSS color picker appears when you specify the color property.
You can use the color picker to select a color and to generate the corresponding code for the
color.
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
<link href="styles/ContactUsStyles.css" rel="stylesheet" type="text/css" />
</head>
Note: HTML IntelliSense provides hints to help ensure that you enter valid HTML. The Pick
URL wizard enables you to quickly select a style sheet.
2. In the Debugging Not Enabled dialog box, click Modify the Web.config file to enable debugging, and
then click OK.
3. Verify that Internet Explorer starts running and displays ContactUs.html. The text for the page should
appear in blue.
4. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
1-36 Overview of HTML and CSS
Note: You can enter some sample data, but do not click Send because the URL that is the
target of the form is not available.
h1 {
font-family: 'Copperplate Gothic';
color: red;
}
5. Verify that the Name field changes to Full name, the Telephone field changes to Telephone
number, and that the style of the heading has changed.
U
Using the
e Internet Explorer FF12 Develloper Tools
As an aid to d
A developers wisshing to inspe ect and debug g how their weeb pages are delivered to ttheir browser,
a also in response to sim
and milar capabilities in other brrowsers, Micro
osoft has provvided the F12 Developer
T
Tools as a feature of Internet Explorer. T
These tools enable a develo oper to quicklyy perform the
e following
t
tasks while the application is running in Internet Explo orer:
• Inspect an
nd validate HTML markup and CSS style
e sheets.
• Run and d
debug JavaSccript code.
• Profile pa
age load timess to optimize an application.
I Internet Exp
In plorer, press F
F12 to displayy the F12 Deve
eloper Tools w
while a web application is rrunning
FIGUR
RE 1.2: THE F1
12 DEVELOPE
ER TOOLS
The menu barr across the to
T op of the Toools window givves you quickk access to som
me Internet Exxplorer
f
features and ssome online document
d valiidation service
es:
• The File m
menu gives acccess to help d
documents an
nd to close the Tools windo
ow.
• The Disab
ble menu enaables you to to
oggle Interne
et Explorer's su
upport for blo
ocking popups, script and
CSS.
• The Images menu enables you to toggle Internet Explorer's support for displaying images along with
the display of information about the images in the page.
• The Cache menu enables you to change Internet Explorer's cache and cookie settings.
• The Tools menu gives access to several useful tools; for example, you can change the user agent
string to emulate the behavior of the page in other browsers.
• The Validate menu allows you to validate your HTML and CSS documents against the current
standards and accessibility checklists.
The rendering engine that displays HTML in the Internet Explorer window changes with each new version,
so the Browser Mode and Document Mode drop-down lists allow you to select which version of
Internet Explorer you wish to mimic to see how it would render your page.
• The CSS tab enables you to inspect any of the style sheets referenced by the current document and
enable\disable any rule or property within a rule to see how that affects the presentation of the page.
• The Console tab lets you view any error messages from Internet Explorer during the execution of the
page.
• The Script tab enables you to step through and debug any JavaScript executing on your page.
• The Profiler tab lets you to examine the performance of each call and function in your JavaScript
code. This feature is useful for determining the hot spots in your application and for highlighting
areas where it may be beneficial to optimize your JavaScript code.
• The Network tab enables you inspect to how and when the various images, style sheets, scripts, and
other resources are downloaded as part of your page, why they were downloaded, and how long they
took to download.
Additional Reading: For further information on how each of the tabs in the F12 Developer
Tools work tabs, visit http://go.microsoft.com/fwlink/?LinkID=267712
Programming in HTTML5 with JavaScrippt and CSS3 1-39
9
S
Scenario
ContosoConf is an annual ttechnical confference that describes
C d the latest
l tools an
nd techniquess for building
H
HTML5 web aapplications. T
The conferencce organizers have
h created a web site to support the cconference,
u
using the sam
me technologie es that the co
onference show
wcases.
O
Objectives
A
After completting this lab, you
y will be able to:
• User Nam
me: Student
• Password
d: Pa$$w0rd
1-40 Overview of HTML and CSS
• The Home page, which provides a brief overview of the conference, the speakers, and the sponsors.
The Home page also includes a video from the previous conference.
• The About page, which provides more detail about the conference and the technologies that it
covers.
• The Schedule page, which lists the conference sessions. The conference has two concurrent tracks,
and the sessions are organized by track. Some sessions are common to both tracks.
• The Register page, which enables the user to provide their details and register for the conference.
• The Location page, which provides information about the conference location and a map of the
venue.
• The Live page, which enables an attendee to submit technical questions to the speakers running the
conference sessions. The page displays the answer from the speaker, together with questions (with
answers) posted by other conference attendees.
• The Feedback page, which enables the user to rate conference sessions and speakers.
X Task 1: Start the web application and view the Home page
1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-01 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
FIGUR
RE 1.3: THE HOME PAGE
The graphics e
T elements for tthe speakers and
a sponsors are implemen
nted by using
g HTML img e
elements. The
s
sources of the
e images are jpg and png files.
6
6. Scroll to tthe bottom off the page and play the vid
deo from the previous
p confference. This functionality
f
is implemmented by usinng the HTML5 5 video elemeent.
Note: Y
You will not he
ear any sound
ds because Hyyper-V does not provide a vvirtual audio
device.
d
7
7. Scroll to tthe top of the
e Home page and hover thhe mouse overr the Registerr Free icon. Notice
N that
the icon rrotates and exxpands as the mouse enterrs the icon. This feature is im
mplemented b
by using CSS.
8
8. At the very top of the page, move the mouse ove er the menu bar
b listing the names of thee pages in the
applicatio m is highlightted as the mouse traverses
on. Do not clicck any menu items. Notice that each item
it. This feaature is imple
emented by ussing an HTMLL nav elementt and CSS.
X Task 2: View
V the Ab
bout and Scchedule pag
ges
1
1. Using the
e menu bar, m
move to the About page.
The Abouut page lookss like this:
1-42 Overview of HTML and CSSS
2. Move to the
e Schedule page.
p
The Scheduule page lookks like this:
X Task 3: View
V the Re
egister page
e and registter as a new
w attendee
1
1. Move to tthe Register page.
The Register page loooks like this:
2
2. Register tthe details forr a new attend
dee.
N
Notice that th
he page perfo
orms the follow
wing validatio
ons:
o All fie
elds apart from Website/b
blog are mand
datory
o The E
Email addresss must be in the
t correct format
o The p
password mu
ust contain at least 5 letterss and numberrs
o The vvalue entered for the Confirm your passsword field must
m he password field
match th
This validation
T n is performed d by using a ccombination oof HTML5 form ms validation controls and JavaScript
c
code. The stylling of the fields when theyy display an errror is controllled by using C
CSS.
W
When you havve successfully registered, the
t confirmattion page app
pears.
3
3. Scroll to tthe bottom off the page. Th
he venue map
p that appearss is generated by using Scalable Vector
Graphics.
X Task 5: Submit
S a qu
uestion and
d provide co
onference fe
eedback
1
1. Move to tthe Live pagee.
The Live page looks likke this:
FIGUR
RE 1.9: THE LIIVE PAGE
The Live page
T e enables an aattendee to su
ubmit questio
ons to a speakker and to view
w the responsse. The page
a displays q
also questions askeed by other attendees.
2
2. Ask a que
estion.
3
3. Review th
he questions tthat are displaayed. This pag
ge also enable
es an attendee
e to report an
ny questions
that they feel are offen
nsive.
4
4. Select a q
question and report
r it. The question will be vetted and
d then disapp
pear.
Questions and
Q d reporting arre managed bby using a webb socket serve
er. The applicaation connectts to this
s
server by opening a client connection
c an
nd sending reequests asynchhronously. As other attende ees post
q
questions, the
e JavaScript co
ode behind th
his page autommatically updates the list of questions th
hat is
d
displayed.
1-46 Overview of HTML and CSSS
5. Move to the
e Feedback page.
p
The Feedbaack page lookks like this:
7. Close Intern
net Explorer.
Re
esults: After co
ompleting thiis exercise, you will be able
e to describe tthe features of the Contoso
o
Co
onference web b application aand list the te
echnologies th
hat are used to implement them.
Programming in HTML5 with JavaScript and CSS3 1-47
X Task 1: Explore the web pages for the application by using Visual Studio 2012
1. In Visual Studio, view the index.htm file. This file contains the HTML markup for the Home page as
static text. Look at the following items in the file:
o The nav element at the start of the body section defines the menu that appears at the top of the
page (the same menu appears on the other HTML pages as well). The item tagged with the active
class specifies the item that refers to the current page. This item is styled differently when it is
rendered.
o The section with the video class above the page footer which implements the video player.
o The link elements near the top of the file specify the CSS files that provide the styling for this
page. The index.css style sheet contains the styles specifically for this page, while the other style
sheets contain styles that are used throughout the application.
o The script elements just before the closing body tag specify the JavaScript files that implement
the functionality for this page.
2. View the about.htm file. This file contains the HTML markup for the About page as static text. Notice
that:
o This page implements the same navigation menu as the Home page. Notice that the About item
is tagged with the active class.
o Styling is handled by a set of CSS files. The about.css style sheet implements the styling specific to
this page.
3. View the schedule.htm file. This file contains the HTML markup for the Schedule page.
In this page, notice that the list of sessions in the Schedule page section is empty; it is populated
when the page is displayed by using the JavaScript code in the schedule.js script referenced near the
end of the file.
4. View the register.htm file. This file contains an HTML form with validated inputs that an attendee
uses to provide their details.
When the user submits the form, their details are posted to the registration service at the URL
registration/new
5. View the location.htm file. This file contains an HTML page that displays the distance of the user
from the conference site, together with a venue map.
The distance to the conference site is calculated by using JavaScript code that calls the Geolocation
API, in the script location.js. The script displays the distance in the <h2> element with the id of
distance.
1-48 Overview of HTML and CSS
7. View the feedback.htm file. This page contains the feedback form, enabling attendees to provide
their feedback on the conference.
The input fields for the first four questions are rendered as stars by using the JavaScript code in the
StartRatingView.js file and the styles in the feedback.css style sheet. Properties of the input fields
define the maximum and minimum ratings, and each rating is displayed as a single yellow star.
The input field for the comments feedback is a <textarea> element.
When the user submits the feedback, JavaScript code in the feedback.js file and styles in the
feedback.css style sheet animate the form to make it fly off the screen.
o scripts. This folder contains the JavaScript files used throughout the application. The pages
subfolder contains the JavaScript files containing the code that is specific to each page. Each file
is named after the corresponding HTML file.
o styles. This folder contains the styles for the application. It is organized in a similar manner to the
scripts folder. The images subfolder contains the graphic image of a star, used by the feedback
and schedule pages.
Note: For the purposes of this lab you can ignore the Controllers and Views folders. These
folders contain C# and ASP.NET code that implement the web services used by the application. In
the real world, they would be implemented separately from the web application.
You can also disregard the Properties and References folders, which contain items that support
the web services, as does the Global.asax file.
You will not use any of these items in in this course.
3. Edit the HTML markup for the Home page and change the text for the Register Free button to
Register Now.
4. Open the style sheet used to render the contents of the <nav> element and change the background
color to blue.
5. Save the changes, return to Internet Explorer, refresh the view, and verify that you can see the effects
of the changes.
Programming in HTML5 with JavaScript and CSS3 1-49
Results: After completing this exercise, you will be able to describe how the Contoso Conference
application is structured as a Visual Studio 2012 project.
1-50 Overview of HTML and CSSS
Modu
ule Reviiew and
d Takea
aways
M
Module Revie
ew
In this module, yyou have learrned how you can use HTMML to define th
he content, structure, and ssemantics
of a web page, tto use CSS to define the wa
ay in which a web page is d
displayed, and
d to use JavaSScript code
to add dynamicc functionalityy.
Yo
ou have learne
ed how to writte a basic HTM C selectors tto identify a set of
ML page, and how to use CSS
ele
ements to app
ply presentatio
on rules to, an
nd how to attach both style
e sheets and sscript files to a web
page.
Q
Question
W
What is the be
est way to ap
pply CSS ruless to HTML ele
ements that o
occur in several different
p
pages?
S
Select the corrrect answer.
Question
by using a <stylesheet> element in the <head> element of each page.
2-1
Module 2
Creating and Styling HTML Pages
Contents:
Module Overview 2-2
Modu
ule Ove
erview
Ob
bjectives
e, you will be able to:
Aftter completing this module
• Explain how
w to use CSS tto style the layyout, text, and
d background
d of a web pag
ge.
Programming in HTML5 with JavaScrript and CSS3 2-3
3
Lesson 1
Creatting an
n HTMLL5 Page
e
Many develop
M pers creating w
web applications use HTML5 and CSS3 b because these e technologiess are
l
lightweight, eature-rich, and platform in
fe n about the new features
ndependent. In this lesson, you will learn
o HTML5 thaat are attractin
of ng so many neew developers to it, and ho a structure a page by
ow to create and
u
using some thhe new eleme ents in HTML55.
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain ho
ow to use the
e new HTML5 elements for describing arreas of a docu
ument and maarking up textt.
• Explain ho
ow to use the
e new HTML5 elements for adding hyperrlinks and imaages to a page
e.
2-4 Creating and Styling HTML PPages
W
What's New
w in HTMLL5?
In 1998, the Wo orld Wide Web b Consortium (W3C) decide ed that it had
d finished deveeloping HTMLL and
sto
opped work o on it once verssion 4.01 becaame a web staandard. Howe ever, a small group of indiviiduals
asssociated with this project d
disagreed, and
d continued too develop it th
hemselves. In 2006, W3C re eversed its
deecision based oon the work pperformed by this group, now named the Web Hyperrtext Application
Technology Wo orking Group (WHATWG),
( a started wo
and ork on HTML5 5, based on a subset of the
e features
deefined by WHA ATWG.
HT
TML5 has seve
eral aims:
• Not to "bre
eak the web". HTML5 is bacckwards comp
patible with prrevious versions of HTML.
Note: The
e DOCTYPE de
eclaration wass described in
n module 1.
HT
TML5 defines many other n
new features, including:
i
• The <canvas> element and the associated JavaScript API provide a freeform area in a page to draw
on, and the JavaScript commands to do the drawing, importing and exporting.
• Support to enable web applications to continue running when the browser is offline.
• Support for local data storage, over and above that provided by cookies.
There are also a number of HTML5-associated specifications authored byW3C that are outside of the
wider WHATWG work, including:
• A formalization of the JavaScript object that underpins AJAX by using the XmlHttpRequest object.
• Support for continuous communication between browser and web server by using web sockets.
• Support for using multiple threads to handle processing for a web page by using web workers.
• Support for accessing a device's GPS capabilities by using the Geolocation API.
Reference Links: You can find the current draft of the W3C HTML5 specification at
http://go.microsoft.com/fwlink/?LinkID=267714.
You can find a version of the specification for web developers (minus the browser interoperability
instructions) at http://go.microsoft.com/fwlink/?LinkID=267715.
2-6 Creating and Styling HTML PPages
HT
TML5 includess new elements that enablee you to markk up your conttent and prese
ent a better sttructure for
your documentss compared to
o earlier versions of HTML.
• The <nav> element, which identifies tthe content p providing the main navigatiion sections o
of the page.
Developers often use this element to implement
i a menu listing the
t various features of a we eb
application,, organized ass a series of w
web pages.
Co
ontent Structture in HTML
L5
<
<!doctype htm
ml>
<
<html>
Programming in HTML5 with JavaScript and CSS3 2-7
<head>
<meta charset="utf-8">
<title>My Best Recipes</title>
</head>
<body>
<nav>
<a href="/">Home</a>
</nav>
<header>
<h1>My Best Recipes</h1>
<p>My favorite recipes</p>
</header>
<article>
<h1>Beans On Toast</h1>
<section>
<h1>Ingredients</h1>
<ul>
<li>Beans</li>
<li>Bread</li>
</ul>
</section>
<section>
<h1>Method</h1>
<ol>
<li>Toast bread</li>
<li>Heat beans</li>
<li>Put beans on the toast</li>
</ol>
</section>
</article>
<footer>
<small>Last updated on <time datetime="2012-08-12">August 12, 2012</time></small>
</footer>
</body>
</html>
It is important to realize that there is no prescribed order in which to use these elements. For instance, you
could decide to include your navigation links in the header, footer, or sidebar. Similarly, you could split
your page up into thematic sections (such as Breakfasts, Lunches, and Dinners) and include <article>
elements within those sections. The important thing is to grasp the purpose of each new element and use
it appropriately.
Note: Note how there are three <h1> elements on the page rather than just the one you
would expect. Previously, this would have been semantically incorrect, but the <section> and
<article> elements are defined in HTML5 such that you may restart the heading numbering. The
HTML5 outlining algorithm defines this and the use of <hgroup> in the next topic.
2-8 Creating and Styling HTML PPages
Te
ext and Im
mages in H
HTML5
<hgroup>
<h1>My Recipes</h11>
<h2>Greeat to eat, easy to make</h2>
</hgroup>>
<time dat
tetime="2012
2-08-08">Today</date>
<time dat
tetime="2012
2-08-08T09:00
0:00-0500>9a
am today in New York</time>
<time>4h<
</time>
<time>201
12</time>
• The <mark k> element, wwhich identifies that its conttents should be
b treated as text
t to be marked or
highlighted
d for reference
e purposes.
<p>Heat y
your beans f
for five minutes. <small
l>Or until t
they are hot enough for
you.</sma
all></p>
<figure>
Programming in HTML5 with JavaScript and CSS3 2-9
Additional Reading: HTML5 also adds to the global attributes defined in HTML4. You can
find a full list at http://go.microsoft.com/fwlink/?LinkID=267716.
2-10 Creatingg and Styling HTML Pages
Demonstration: Usin
ng HTML5
5 Featuress in a Simp
ple Contact Form
In this demonstration, you wiill see how to add some of the new HTM ML5 elements to flesh out th he contact
forrm created du
uring the dem
monstrations in n Module 1 an nd add some semantic rich hness. You willl then use
thee F12 Develop
per Tools to vview the structture of the page. You will aalso see how to use the F12
2 Developer
To
ools to make a temporary change to a paage for testing g purposes in a browser.
De
emonstration Steps
Divvide the Conttent for a Page
e into an Articcle with Sectio
ons
1. On the Win udio 2012 tile.
ndows 8 Start screen, click the Visual Stu
2. In Visual Stu
udio, on the F
File menu, point to Open, and
a then clickk Project/Solution.
3. In the Open
n Project diallog box, brow
wse to the E:\D
Democode\Starter folder, click DemoW
WebSite.sln
and then click Open.
<!DOCTYPE HTML>
<html lang="en">
...
</head>
<body>
<article
e>
...
</article>
</body>
</html>
...
<h1>Contact Contoso C
Conferencing
g</h1>
<section>
Programming in HTML5 with JavaScript and CSS3 2-11
7. Wrap the HTML form and <p> element immediately above it in a second <section> element, as
shown in bold in the following code example:
...
<section>
<p>
If you would like to contact Contoso Conferencing ...
</p>
<form method="POST" action="support.aspx">
...
</form>
</section>
...
1. Enclose the <h1> element near the top of the ContactUs.html file in a <header> element, as shown
in bold in the following code example:
...
<article>
<header>
<h1>Contact Contoso Conferencing</h1>
</header>
...
</article>
...
2. Add the following <img> element shown in bold to the <header> element above the <h1>
element.
<header>
<img src="images/Contoso.png" alt="Company Logo" />
<h1>Contact Contoso Conferencing</h1>
</header>
3. Add the following HTML markup shown in bold immediately after the </article> tag near the end of
the document.
...
</article>
<footer>
<p>
<small>
Last updated
<time datetime="2012-08">
August 2012
</time>
2-12 Creating and Styling HTML Pages
</small>
</p>
</footer>
</body>
</html>
2. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
3. Press F12.
7. Expand the <article> element and verify that it contains a <header> element and two <section>
elements.
Make a Temporary Change to the Page by Using the F12 Developer Tools
1. In the <h1> element, click Contact Contoso Conferencing .
2. Change this text to We'd love to hear from you…, and then press ENTER.
Lesson 2
Stylin
ng an H
HTML5 Page
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to
• Explain ho
ow to use the
e CSS box mod
del to position
n elements on
n a page.
Understand
ding CSS Text
T Styless
Fo
onts
The most obvious aspect of ttext content iss the font. The e discussion o
of when to use e which type o
of font for
he many organizations have
eadings, body text, sidebarss, and so on iss outside the sscope of this ccourse. Also, m
That said, you can use the ffollowing CSS properties
styyle guides that specify the ffonts for theirr web pages. T
to set the selectted font.
• The font-fa amily propertty, which sets a comma-sep parated list off preferred fon
nt families forr the
specified te
ext. You should
d write the lisst in order of p
preference an nd wrap any fo ont-family nam mes
containing spaces in douuble quotes. WWhen the text is rendered, the t browser w will use the firsst font that
is available on the computer. If none o of the specifie
ed fonts are avvailable, the browser
b will usse its own
algorithm to select anothher font. The ffollowing cod de shows some e examples:
font-fami
ily : Arial, Candara, Verdana, sans
s-serif;
font-fami
ily : Georgia, Corbel, "Times New R
Roman", serif;
font-fami
ily : Consolas, "Courier New", mono
ospaced;
font-size
e : 16px;
font-size
e : 150%; /
/* Font-size of the pare
ent element * 150% */
font-size
e : 1em; /
/* 1em = base font-size of the page
e. Usually 16px */
font-styl
le : italic;
Programming in HTML5 with JavaScript and CSS3 2-15
• The font-weight property, which enables you to set the weight of a font. Usually, this means setting
the property value to bold, but you can also set it to one of nine numerical values (100, 200, … , 900)
reflecting different font weights in that family (black, book, semi-bold, and so on). The following code
shows some examples:
font-weight : bold;
font-weight : normal;
font-weight : 800;
CSS also provides a shortcut property simply called font, which enables you to set some or all of these
four properties (plus line-height) in a single rule rather than having to write out all five rules for every
element. You must set the value for these properties in the following order:
1. font-style
2. font-weight
3. font-size/line-height
4. font-family
For example:
Colors
There are two color-related properties in CSS: color and opacity.
• The color property, which enables you to set the color of a font. You can specify the color as an RGB
(red-green-blue) value or as one of the 147 predefined color names in the HTML and CSS
specification. The following code shows some examples:
• The opacity property, which enables you to set the transparency of some text or of an image. This
property takes a value between 0.0 (fully transparent) and 1.0 (fully opaque). The following code
shows an example:
p {
opacity : 0.6;
filter:alpha(opacity=60); /* IE8 and earlier */
}
Note that Internet Explorer versions prior to Internet Explorer 9 do not support the opacity property.
Instead, you must use the filter property and set the opacity to a value between 0 and 100.
Typographic Properties
CSS defines another five text-related properties that cover typographic properties such as line height and
kerning, as well as more obvious features such as alignment and underlining. These properties are:
2-16 Creating and Styling HTML Pages
• The letter-spacing property, which enables you to increase or decrease the space between characters
in a block of text. You can set the font-size value to an absolute value in pixels or points, or to a
relative value in percentages or in ems. The following code shows some examples:
letter-spacing : 2em;
letter-spacing : -3px;
• The line-height property, which enables you to increase or decrease the space between lines of text
in a block of text. You can set this value to an absolute value in pixels or points, or a value relative to
the current font-size by using either a percentage or a positive number. The following code shows
some examples:
line-height : 16px;
line-height : normal; /* This is the default */
line-height : 1.2;
line-height : 120%;
• The text-align property enables you to set how the text in the selected blocks is aligned. For
example, left, right, or justify. The following code shows an example:
text-align : left;
• The text-decoration property, which enables you to set whether text in selected elements will be
decorated with a line, and if so, where. Possible values are none (the default), underline, overline, and
line-through. The following code shows an example:
text-decoration : underline;
• The text-transform property, which enables you to set the capitalization of text in selected blocks.
Possible values are none (the default), capitalize, uppercase, and lowercase. The following code shows
an example:
text-transform : lowercase;
Note: If you are using Visual Studio to define new styles, you can use the Build Style
wizard to generate these styles and to ensure that the syntax of your CSS code is valid. This
wizard is available in the toolbar in the CSS editor.
Programming in HTTML5 with JavaScrippt and CSS3 2-17
7
T CSS B
The Box Model
FIGUR
RE 2.1: THE CS
SS BOX MOD
DEL
IIn the center box is the conntent, your te
ext and image
es. Use the heiight and width properties to set the
h
height and wiidth of the content box in p
pixels.
Around the co
A ontent box is the padding box. Use the padding pro
operty to set th
he width of th
he padding
b
box.
A
Around the border box is the margin bo
ox. Use the m
margin properrty to set the w
width of the m
margin box.
The following code example shows how to use the CSSS box model to draw a bo
T order around ssome padded
h
heading text and
a to set a m
margin around e with other elements on
d the border sso that it doess not interfere
t page.
the
2-18 Creating and Styling HTML Pages
Margin and padding are both shorthand properties. CSS actually defines individual properties for the
top, right, bottom, and left of each box, but if they are the same, you can just use padding or margin. In
the previous code example, padding is set to 10px. You could write this out in full as:
padding-top: 10px;
padding-right : 10px;
padding-bottom : 10px;
padding-left : 10px;
Reader Aid: You can easily recall the order of the sides by thinking of the word TRouBLe:
Top, Right, Bottom, and Left.
Border is also a shorthand property for the width, style, and color of the border box. In the previous
example, border is set to 2px dotted blue. You could write this out in full as:
border-width: 2px;
border-style: dotted;
border-color: blue;
Using the border-width, border-style, and border-color properties assumes that you want the set
values to be the same around all four sides of the box. If this is not the case or you only want to set them
for one side of the border, you can use the border-left-style, border-left-width, border-left-color,
border-right-style, border-right-width and so on properties. For example:
p.example {
padding: 10px;
border-bottom: solid 1px black;
border-left-style: dotted;
border-left-width: 2px;
}
The border-top, border-right, border-bottom, and border-left properties are also shorthand
properties, like border, but for the width, style, and color of the respective sides of the border box.
Note: Note that the F12 Developer Tools offer you a graphic illustrating the dimensions of
each box in a page. To see the illustration, with a page loaded in Internet Explorer, select the
HTML tab, and then click Layout in the right pane.
Beyond the core box model properties, CSS defines several more properties to control how content is
viewed in the flow of the elements on the page. Specifically:
• The visibility property enables you to blank out the selected elements, but leave the space that they
would take up on the page empty.
• The display property enables you to set how to display selected elements on the page. This includes
hiding the selected elements, or completely removing them from the page.
Programming in HTML5 with JavaScript and CSS3 2-19
• The position property enables you to set positioning method for the selected elements are
positioned. The four possible values are static (the default), fixed, absolute, and relative.
• The float property enables you to take the selected elements out of the flow of content and 'float'
them to the left or right of their containing elements.
• The overflow property enables you to set what happens when the content of an element is too big
for the box that contains it.
• The box-sizing property enables you to set how the width and height properties apply to an
element's box model. If set to content-box (the default), they work as described above. If set to
border-box, the width and height apply to the total of content, padding, border and margin taken
together.
2-20 Creatingg and Styling HTML Pages
Maany websites u
use a backgro
ound image, color,
c or patte
ern to provide
e more color and
a character to the
pages. CSS enab
bles you to set a backgroun
nd for any blo
ock-level elem
ment by using the following
g elements.
backgroun
nd-image:url('pattern.jpg');
backgroun
nd-size: 40p
px 60px; /* 40px wide, 60px high *
*/
backgroun
nd-color : g
green;
backgroun
nd-color : #
#00FF00;
backgroun
nd-color : r
rgb(0, 255, 0
0);
• The backgrround-positio on property, w which enabless you to set th he position off the backgrou und image
in the element. The prop
perty takes two o values: the ffirst for the x--axis and the second
s for the
e y-axis. Set
them both as absolute vaalues (top, lefft, bottom, right, center), pe ercentages, orr pixels.
backgroun
nd-position : left top; /* Image llocked into top left corner of elem
ment */
backgroun
nd-position : 100% 100%; /* Image locked intoo bottom right corner of
f element
*/
backgroun
nd-position : 8px 8px; /
/* Image sta
arts 8px fro
om left and 8px from top
p of
element *
*/
background-origin : border-box;
• The background-repeat property, which enables you to set how a background image is repeated
behind the selected element if it is smaller than the selected element. Possible values are repeat (the
default), repeat-x, repeat-y and no-repeat.
• The background-attachment property, which enables you to set whether a background image
scrolls up and down with a page or remains fixed in place. Possible values are scroll (the default) and
fixed.
background-position : fixed;
CSS also provides the background shortcut property which enables you to set some or all of the elements
just described. You must set the values for these properties in the following order:
1. background-color
2. background-position
3. background-size
4. background-repeat
5. background-origin
6. background-clip
7. background-attachment
8. background-image
For example:
Demonstration: Add
ding CSS S
Styles to aan HTML P
Page
In this demonstration, you wiill see how to create new sttyles for the contact form ccreated during
g the
pre
evious demon nstrations. You u will then vie
ew the page in
n Internet Exp
plorer and use
e the F12 Deveeloper
To
ools to inspectt the styles of elements and d to modify th
hem to see hoow they are re
endered by thee browser.
Note: If yo
ou have not ccompleted thee previous demonstration, use the websiite in the
E:\\Democode\S Solution fold n the project iin the E:\Dem
der rather than mocode\Startter folder for
thiis demonstrattion.
De
emonstration Steps
Cre
eate New Stylles by Using Visual
V Studio
1. On the Win
ndows 8 Start screen, click the Visual Stu
udio 2012 tile.
2. In Visual Stu
udio, on the F a then clickk Project/Solution.
File menu, point to Open, and
3. In the Open
n Project diallog box, brow
wse to the E:\D
Democode\Starter folder, click
DemoWeb bSite.sln, and then click Op
pen.
5. Double-clicck ContactUsS
Styles.css
7. Modify the body rule, reemove the color rule, and cchange the fon
nt used on the whole page
e as shown
in bold in th
he following ccode example
e.
body
{
font-fam
mily: "Segoe UI",
U Helvetica
a, Arial, sans-serif;
}
8. Remove the
e following ru
ule from the sttyle sheet:
h1 {
Programming in HTML5 with JavaScript and CSS3 2-23
9. Add the following rules that make the header appear separate from the rest of the content.
header {
padding-bottom: 10px;
border-bottom: 2px dotted blue;
margin-bottom: 10px;
}
header h1 {
margin-left: 20px;
display: inline-block;
}
section {
}
11. Click after the opening curly brace for the section rule, and in the toolbar click the Build Style
button.
12. In the Modify Style dialog box, in the Category list, click Box.
13. Clear the padding: Same for all check box, and in the bottom box, type 5.
14. In the Category list, click Border.
15. Under border-style, clear the Same for all check box, and in the bottom list box, click dotted.
16. Under border-width, clear the Same for all check box, and in the bottom box, type 1.
17. Under border-color, clear the Same for all check box, and in the bottom box, type grey.
19. Verify that the section rule now looks like this:
section {
padding-bottom: 5px;
border-bottom-style: dotted;
border-bottom-width: 1px;
border-bottom-color: grey;
}
20. Add the following rules to style the form and its elements.
fieldset {
background-color: pink;
margin-bottom: 10px;
}
legend {
font-size: 1.2em;
font-style: italic;
}
fieldset li {
list-style: none;
margin-bottom: 10px;
}
input[type="submit"] {
background-color: pink;
opacity: 0.6;
width: 200px;
2-24 Creatingg and Styling HTML Pages
2. On the Deb
bug menu, click Start With
hout Debugg
ging.
4. Verify that tthe new styless have been aapplied to the page.
The ContacctUs page should look like tthis:
font-family: "Segoe U
UI", Helvetica, Arial, sans-serif;
10
0. Change the
e value to read
d "Times New
w Roman" an
nd press ENTE
ER.
12. In the left pane, expand the <body> element, expand the <article> element, and then click the first
<section> element.
13. In the right pane, verify that the following styles are specified for this section:
inherited – body
body
font-family: "Times New Roman", Helvetica, Arial, sans-serif;
section
padding-bottom: 5px;
border-bottom-color: grey;
border-bottom-width: 1px;
border-bottom-style: dotted;
15. Close Internet Explorer, and then close Visual Studio 2012.
2-26 Creatingg and Styling HTML Pages
Lab: C
Creating
g and Styling
S HTML5
5 Pages
Sccenario
Yo
ou are a web d developer worrking for an o
organization th
hat builds websites to supp
port conferencces. You
have been asked d to create a w
website for Co
ontosoConf, a conference that
t showcasees the latest to
ools and
tecchniques for b
building HTML5 web appliccations.
Ob
bjectives
Aftter completing this lab, you
u will be able to:
• ML5 pages
Create HTM
First you will create a new ASP.NET Web Application. Then you will add two HTML files for the Home and
About pages. Next, you will add navigation links to the pages. Finally you will run the web application and
verify that the Home page and About page are formatted correctly.
2. Start the 20480A-SEA-DEV11-02 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio.
1. Create a new Visual C# ASP.NET Empty Web Application named ContosoConf in the
E:\Labfiles\Starter\Exercise 1 folder.
2. Add HTML elements to index.htm, using the text provided in the index.txt file located in the
E:\Labfiles\Starter\Exercise 1\Resources folder.
• Use HTML5 elements, such as <header>, <section>, and <footer> where appropriate.
2-28 Creatingg and Styling HTML Pages
The following im
mage shows h how the unstyyled page shou
uld look, and how the conttent should be
e divided
intto the elemen
nts on the pag
ge.
X Task 3: Ad
dd images tto the Home Page
1. Add the spe eaker and spoonsor images to the ContossoConf projecct. These imag ges are located
d in the
E:\Labfiles\SStarter\Exercisse 1\Resource
es folder. Theyy should be ad
dded to a new
w folder called
d images in
the project..
2. Update spe
eaker and sponsor HTML markup
m in the index.htm
i file to include tthe images fro
om the
speakers and sponsors folders in the
e images folde
er.
Programming in HTTML5 with JavaScrippt and CSS3 2-29
9
FIGUR
RE 2.4: THE HOME PAGE WITH
W IMAGE
ES
Note: In
n an <img> e
element, you ccan use the Pick
P URL wizard to specify the
t src attribu
ute
f an image.
for
X Task 4: Add
A the Ab
bout page
1
1. Add a new
w HTML page
e, named abo
out.htm to the
e ContosoCon
nf project.
2
2. Add HTMML elements too about.htm,, using the texxt provided in xt file located in the
n the about.tx
E:\Labfile
es\Starter\Ex
xercise 1\Ressources folder.
• Re-use th
he <header> and <footer> elements frrom index.htm
m.
• Use the <
<article>, <blockquote>, and<ol> elem
ments where appropriate.
2-30 Creatingg and Styling HTML Pages
The following im
mage shows h
how the unstyyled page shou
uld look.
X Task 5: Ad
dd navigatio
on links
1. Add a navig
gation elemen
nt to index.httm and about.htm. The naavigation elem
ment should ccontain links
to both pag
ges.
X Task 6: Ru
un the web application
n
1. Run the web application by using Inte
ernet Explorerr.
Re
esults: After co
ompleting thiis exercise, you will have bu
uilt a simple H
HTML5 web ap
pplication with a Home
page and an Ab bout page.
Programming in HTML5 with JavaScript and CSS3 2-31
You will create a style sheet in the ContosoConf project. Then you will add CSS rules to style the Home
and About pages to match a specified design. Finally, you will run the web application and verify that the
pages are styled correctly.
3. Add a link to the site.css stylesheet from the index.htm and about.htm HTML5 pages
• You will need to modify the HTML markup for the Home and About pages, wrapping elements in
<div class="container"> elements and adding a corresponding .container rule to the stylesheet to
achieve the horizontally centered, fixed-width column effect.
2-32 Creatingg and Styling HTML Pages
X Task 3: Ru
un the web application
n
1. Run the web application and verify that the About page and Home page are both styled
appropriate
ely.
The About page should look
l like this in plorer:
i Internet Exp
Re
esults: After co
ompleting thiis exercise, you will have ussed CSS rules to style the Home and Abo
out pages.
Programming in HTTML5 with JavaScrippt and CSS3 2-33
3
Module Rev
view an
nd Take
eaways
M
Module Rev
view
IIn this modulee, you have le
earned how to
o use the new features of HTML5
H to orgaanize the conttent for a
w page. You have seen h
web how to use the
e new tags avvailable in HTM
ML5 to specifyy the semantiics of the text
e
elements in a web page.
Question
n: What are th
he new elements that HTML5 provides fo
or specifying tthe semantic
meaning of content in a web page?
T
Test Your Kno
owledge
Question
Which of the following ittems is NOT a property off the CSS boxx model?
Marrgin
Content
Bord
der
Style
e
Padd
ding
3-1
Module 3
Introduction to JavaScript
Contents:
Module Overview 3-2
Modu
ule Ove
erview
HTTML and CSS p provide the sttructural, semantic, and preesentation information for a web page. H However,
theese technolog gies do not de escribe how thhe user interacts with a pag
ge by using a browser. To im mplement
thiis functionalityy, all modern browsers incllude a JavaScrript engine to
o support the use of scripts in a page.
They also implement the Doccument Objecct Model (DOM M), a W3C staandard that de efines how a bbrowser
shoould reflect a page in mem mory to enable e scripting eng
gines to accesss and alter th
he contents off that page.
Ob
bjectives
Aftter completing this module
e, you will be able to:
Lesson 1
Overrview of JavaScript
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain th
he purpose off JavaScript.
• Create an
nd call JavaScrript functions..
W
What is Jav
vaScript?
JavvaScript origin
nated as a pro
ogramming laanguage in the e 1990s and hhas steadily evvolved. The sttandard
up
pon which it iss based, ECMA A-262, is frequ
uently update
ed and augme ented. Conseq quently, the JaavaScript
engines used in modern brow wsers are noww exponentially faster and more
m functionnal than their
preedecessors.
• The ability to
t create obje
ects with prop
perties, metho
ods, and even
nts.
• Add or rem
move items to a list displaye
ed on a page.
• Add, chang
ge, or remove text on a pag
ge.
• Change the
e CSS styles ap
pplied to a sett of elements on the page.
• Obtain info
ormation abou ut the browser displaying th
he web page, such as the manufacturer
m and
d even environmental inforrmation such as the currentt window size
version, and e and local tim
me.
• Display an alert
a in the usser's browser.
dditionally, the
Ad e combination
n of JavaScrip
pt and the XM
MLHttpReque est API (comm
monly referred d to as
AJA
AX) enables a web page too make asynch hronous requeests back to th
he web serverr. The JavaScriipt code for
Programming in HTML5 with JavaScript and CSS3 3-5
a page can use this feature to query a server for more information, without requiring that the entire page
be reloaded in the browser.
Note: JavaScript is not Java. It was originally named Mocha and then LiveScript before its
creator, Brendan Eich, became a Sun employee and Sun decided to rename it JavaScript. The
standards name for the language is ECMA-262 because Sun would not license the JavaScript
name to the standards body. Microsoft's implementation of ECMA-262 is called JScript.
3-6 Introducttion to JavaScript
JaavaScript S
Syntax
Sttatements
A statement
s is a single line off JavaScript. Itt represents an operation to be executed d. For example, the
deeclaration of a variable, the assignment of o a value, or tthe call to a fu
unction. The ffollowing code
e
fraagments show w some examp ples:
var thisV
Variable = 3
3;
counter = counter + 1;
GoDoThisT
Thing();
Alll statements in
n JavaScript should be writtten on a single line and bee terminated w with a semicolon. The
excception to thiis rule is that you
y can split a large string over several llines (for read
dability) by usiing a
backslash. For eexample:
document.
.write("An incredibly really \
very lo
ong greeting
g to the world");
Note: The
e semicolon te
erminator is actually option nal. However, if you do nott terminate
staatements with hey should have been place
h a semicolon,, JavaScript atttempts to discern where th ed,
sometimes with unintended results.
r
Yo
ou can combin ne statementss into blocks, ddelimited by o
opening and cclosing curly braces,
b { and }. This
synntax is used b
by many comm mon programming constructs such as functions, if, sw witch, while, aand for
staatements, which are discusssed later in this lesson.
Co
omments
Coomments enab ble you to addd descriptive notes and doccumentation to your JavaScript code. Th he
JavvaScript interppreter does noot treat commments as part of the code and does not aattempt to un nderstand
theeir contents. JJavaScript sup
pports two diffferent styles o
of comment: m
multi-line commments that begin
b with
/* and end with h */, and single-line comme ents that begin with // and
d finish at the end of the lin
ne.
Programming in HTML5 with JavaScript and CSS3 3-7
Comments should describe the purpose or the reasoning of your code in plain English, to enable you or
another developer to understand it quickly.
Vaariables, D
Data Types, and Op
perators
Va
ariables
Vaariables are ussed to store da
ata. There are
e three ways to
o declare a va
ariable:
greeting = "Hello";
2. Declare it w
without giving g it a value by using the varr keyword. Un
ntil a variable is given a valu
ue,
JavaScript w
will return its value
v as unde
efined.
var myste
ery;
3. Combine th
he above two approaches (this is the recommended sttyle).
Be mind, try to avvoid giving vaariables similar names that are differentiaated only by letter
earing this in m l
cassing, such as valueOfMilk
v and ValueOffMilk. Use desscriptive name es that will make your code e easier to
un
nderstand and d to debug. Foor example, seelectedTime, preferredTra ack, currentS Session.
Da
ata Types
Unnlike C#, Visuaal Basic, and o
other common n programminng languages,, you cannot specify
s the typpe of a
variable in JavaSScript. You deeclare it with tthe var keywo
ord, and then JavaScript atttempts to disccern its type
forr you. JavaScript recognizess three simple e types:
var simpl
le = "Green Eggs and Ham
m";
Programming in HTML5 with JavaScript and CSS3 3-9
2. Number: Any integer or decimal number. Do not wrap a number between double quotes when you
declare a numeric variable or it will be treated as a string.
JavaScript also converts data between types, which can lead to confusion if you are not careful. For
example, the numeric value 0 evaluates to false in Boolean expressions, so it is important to use the
correct operator when comparing the values of variables.
Note: Remember that if you declare a variable but do not give it a value, the variable is
undefined. You can also declare a variable and set it to null. This indicates that a value does not
exist, rather than that it has not been given. It is important to understand the difference.
You can determine the current type of data in a variable by using the typeof operator:
Operators
An operator is a keyword or a symbol indicating how to combine one or more values into an expression.
For example, the addition operator + indicates that two numbers should be added together. There are six
groups of operators in JavaScript:
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
++ (increment)
-- (decrement)
x=y
x += y (x = x + y)
x -= y (x = x - y)
x *= y (x = x * y)
3-10 Introduction to JavaScript
x /= y (x = x / y)
x %= y (x= x % y)
6. Comparison operators determine if two values/variables are or are not equal. The first set of
comparison operators converts the two values/variables to the same type before comparison.
The second set of two comparison operators does not convert the two values/variables to the same type
before comparison.
?: assigns one of two values to a variable based on a condition. For example, the expression x =
(condition)?value1:value2 sets x to value1 if condition is true, value2 otherwise.
• 0, "" (the empty string), undefined, and null all evaluate to false in Boolean operations. Always use
=== when comparing to any of these values.
var zero = 0;
var emptyString = "";
var False = false;
zero == False; // returns true;
zero === False; // returns false;
emptyString == False; // returns true;
emptyString === False; // returns false;
Programming in HTTML5 with JavaScrippt and CSS3 3-11
1
F
Functions
s
A function is a named sequ uence of stateements that pe erform a speccific task. Funcctions are usefful for
d
defining reusaable blocks off code. After itt has been de
efined, a functtion can be caalled from elseewhere in the
s
script and the
e sequence of statements th hat constitutee the function will run beforre execution rreturns to the
n
next statemen nt after the on
ne that called the function.
F
Function defin
nitions in JavaaScript all havve the same syyntax:
functio
on aName( argument1, arg
gument2, …, argumentN ) {
state
ement1;
state
ement2;
…
state
ementN;
}
T
There are four parts to a fu
unction declarration:
• A commaa-separated lisst of values, caalled argumeents, which yoou can pass to o the functionn. This list is
enclosed in parenthese
es. If the functtion has no arrguments, it should still havve the pair of parentheses
after its n
name.
A function that calculates a result can use the return statement to pass this result back to the statement
that called the function. What happens when the value is returned depends on how the function was
called.
For example, if you wanted to calculate the total hotel bill for a guest, you might write the following
function and call it like so.
Note: Not all functions have a name. You can even declare anonymous functions. You
typically use anonymous functions when writing code to handle events or implement callbacks. In
these cases, the function is invoked by the browser (or whatever environment your code happens
to be running in) rather than by your code, and it is referenced by a variable rather than its name.
For an example, see the topic "Handling Events in the DOM" in the next lesson.
You can declare a local variable within a function. Only the statements within that function can use it. It
will disappear and be removed from memory when the function has finished.
You can also declare global variables. A global variable is a variable declared in your JavaScript code
outside of a function. Any function on a web page that references your JavaScript code can use the global
variable. A global variable remains in memory until the page is closed.
Programming in HTTML5 with JavaScrippt and CSS3 3-13
3
C
Condition
nal Statem
ments
if (Tot
talAmountOwed > AdvanceP
Paid) {
Gene
erateNewInvoice(); // rruns if cond
dition is true
}
Note: A block of cod de in JavaScrippt starts with aan opening cuurly brace, {, aand terminatees
with a closing
w g curly brace, }.} The stateme ents inside theese braces are
e executed if the
t expression n
s
specified by the if statement evaluates tto true. JavaSccript uses this same block structure to de elimit
o
other syntactiic structures, ssuch as the else clause of aan if statemennt, or the code e for looping
s
statement escribed later in this lesson)).
(de
AAn if statement can have an optional elsse clause thatt runs a block of code if the
e Boolean
ccondition is faalse.
if (Tot
talAmountPaid > AdvanceP
Paid) {
Gene
erateNewInvoice(); // rruns if cond
dition is true
} else {
WishG
GuestAPleasantJourney(); // runs
s if condition is false
}
2
2. A switch statement pe erforms a seriees of comparisons against an a expression and runs the e series of
statements code where e the compariison matches the value of tthe expression n specified byy a case
clause. Ass with the if sttatement, the
e expression must
m be enclossed in round brackets.
b The body of the
switch statement is a ssingle block, aand execution n runs until it meets the breeak statement, when it
jumps to the first stateement after thhe closing } that indicates thhe end of the switch statem ment block. Iff
there is no break state ement, executtion continuess into the code for the nextt case (which might not be
what you want to happ pen, so watchh out for bugs caused by missing break statements
s in your code).
The code e for the optioonal default case run if no previous case es match.
3-14 Introduction to JavaScript
var RoomRate;
switch (typeOfRoom) {
case "Suite":
RoomRate = 500;
break; // Use break to prevent code in next case statement being run.
case "King":
RoomRate = 400;
break;
default: // code to be executed if typeOfRoom does not match above cases.
RoomRate = 300;
}
Best Practice: Note that in the above switch example, if the value of typeOfRoom is suite
or king, RoomRate will be set to 300 because JavaScript is case sensitive. To solve this, make the
text all lowercase using switch (typeOfRoom.toLowerCase()) and write all the case values in lower
case.
Programming in HTTML5 with JavaScrippt and CSS3 3-15
5
L
Looping S
Statementts
LLooping state
ements enable e you to iteratte through a sset of stateme
ents a numberr of times or u
until a
B
Boolean conddition is met. T
There are threee types of loooping statemeents in JavaScript:
• A while lo oop evaluatess a Boolean co ondition, and then runs thee accompanyiing block of code if this
condition n is true. The ccondition is th d again, and iff it is still true the block of ccode runs
hen evaluated
again. This process con ntinues until the Boolean coondition evalu uates to false.. If the conditiion evaluates
to false im
mmediately, the block of co ode might nevver be run. Fo
or example:
while (GuestIsStil
( lCheckedIn()
))
{
numbe
erOfNightsStay += 1;
}
• A do whiile loop runs a set block of code and the en evaluates a Boolean con ndition. If the condition is
true then the block of code runs agaain and the co ondition is ree
evaluated. The e process repeats until the
condition
n is false. Note
e that the blocck of code alw
ways runs at le
east once. Forr example:
do {
eatAR
RoundOfToast();
} while
e (StillHungry())
for (in
nt i=0; i<10; i++) {
Plump
pUpAPillow();
}
reaches a break statement, the loop stops running and execution continues with the first statement after
the body of the loop.
Programming in HTTML5 with JavaScrippt and CSS3 3-17
7
U
Using Objject Typess
• The Strin
ng object typee, which enablles you to han
ndle strings off text. The Strring type provvides
propertie
es such as leng
gth that returrn the number of characterrs in a string, aand methods such as
concat wwhich you can use to join strings togetheer, together with other methods that enaable you to
convert a string to upp h a string to find a substring
per or lower case, or search g.
var eve
entWelcome = new String(
('Welcome to
o your conference');
var len
n = eventWelcome.length;
Note: N
Notice that you use the new
w operator to instantiate vaariables using the object tyypes.
var tod
day = new Date(134645400
00); // Numb
ber of milliseconds sinc
ce 01/01/197
70
var tod
day = new Date("Septembe
er 1, 2012")
);
var tod
day = new Date(2012, 8, 1); // Notte January is 0, .., Dec
cember is 11
1.
var emp
ptyThreeItemArray = new Array(3);
var sea
asonsArray = new Array("
"Spring", "S
Summer", "Autumn", "Wint
ter");
var thirdSeason = seasonsArray
y[3]; // Win
nter
Note: U
Use square braackets, [, and ], to access an
n element in aan array.
3-18 Introduction to JavaScript
You can also use array-literal notation to create and populate an array:
• The RegExp object type, which enables you to create and work with a regular expression for
matching strings. Use the test method to determine whether a string matches a regular expression.
JavaScript also defines some singleton object types. You do not use these types to declare your own
variables, rather you use the functionality that these types provide. These singleton objects include:
• The Math object gives you access to various mathematical constants (for example, Pi and E) and
functions (sine, cosine, square root, and a pseudo-random number generator) as static properties and
methods. For example, Math.E, Math.cos(); var seed = Math.random();
• The Global object contains global functions and constants and is the parent object for the
undefined, NaN, and Infinity constants. It cannot be instantiated.
Additional Reading: You can find details for all these objects at
http://go.microsoft.com/fwlink/?LinkID=267718.
Programming in HTTML5 with JavaScrippt and CSS3 3-19
9
D
Defining A
Arrays of Objects b
by Using JS
SON
JJavaScript Obj
bject Notation, or JSON as it is more com mmonly known n, is a syntax for
f representing one or
m
more instance
es of an objecct and the valu
ues of their prroperties as a string; a proccess known ass serialization.
T basic synttax is as follow
The ws:
var myOObject = {
"pro
opertyName1" : "property
yValue1",
"pro
opertyName2" : "property
yValue2",
… ,
"pro
opertyNameN" : "property
yValueN"
};
T
There are a fe
ew basic rules::
• Property names and vaalues are sepaarated by a co
olon.
• All prope
erty names and
d values mustt be double-q
quoted stringss.
• Trailing commas in objjects and arraays are forbidd
den.
A serialized co
ollection of ob
bjects is deno
oted as a commma-separated
d list of serializzed objects en
nclosed in a
p of square
pair e brackets. Forr example, here are the two objects serializzed into JSON.
o Attendee o
var att
tendees = [
{
"name": "John Smith",
"currentTrack": "1"
},
{
"name": "W
William Brownn",
"currentTrack": "1"
}
]
Lesson 2
Intro
oduction to the Docu
ument O
Object Model
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Select ele
ements by usin
ng the DOM.
• Add, remove and mod
dify elements by
b using the D
DOM.
Th
he Docum
ment Objecct Model
• The DOM SStyle Model, wwhich defines a set of interffaces for accesssing any type
e of style shee
et and the
CSS rules w
within them.
• The DOM TTraversal and Range Models, which defin ne APIs for traaversing the elements in a w
web page
and manipu
ulating sets off elements at once rather th
han one at a time.
t
• The DOM HHTML API, which defines ob bjects and me
ethods represe
enting each tyype of elemen
nt in the
HTML 4.01 and XHTML 11.0 specificatio
ons.
Note: The
e DOM was de esigned to bee independentt of any one p programing laanguage.
Ho
owever, as broowsers tend only to have JaavaScript interrpreters installed in them, p
programming
g
witth the DOM has
h become syynonymous withw client-side e JavaScript programming.
Programming in HTML5 with JavaScript and CSS3 3-23
3-24 Introducction to JavaScript
Finding Ele
ements in the DOM
• The forms array contains details of alll the forms in the documen
nt.
• The anchorrs array contaains all the <a> tags in the document wiith a name atttribute.
<form nam
me="contactF
Form">
<input
t type="text
t" name="nameBox" />
</form>
Yo
ou can access the DOM object representiing the form in
i the followin
ng ways:
document.
.forms[0] // forms is a zero-base
ed array
document.
.forms["cont
tactForm"]
document.
.forms.conta
actForm
document.
.contactForm
m
Yo
ou can also acccess the DOM
M object repre
esenting the te
extbox in this form in severral ways, inclu
uding:
document.
.forms.conta
actForm.elements[0]
document.
.forms.conta
actForm.elements["nameBo
ox"]
document.
.forms.conta
actForm.nameBox
document.
.contactForm
m.nameBox
Programming in HTML5 with JavaScript and CSS3 3-25
Alternatively, the DOM defines methods on the document object that retrieve elements based on the
value of their ID and name attributes. You can use these methods to quickly find a matching element
without having to traverse the path to that element. These methods include:
• document.getElementById( IdString ), which returns the single element whose ID attribute has the
value specified by IdString.
• document.getElementsByName( NameString ), which returns an array of elements whose name
attribute has the value specified by NameString.
The following example shows how to obtain a reference to the nameBox textbox in the form by using the
getElementById method:
Ad
dding, Removing, and
a Manip
pulating O
Objects in the DOM
M
• document.ccreateElementt(tagname)
• document.ccreateTextNod
de(string)
• document.ccreateAttributte(name, value
e)
• document.ccreateDocume
entFragment
• appendChiild(newNode
e), which addss the new nod
de as the last child
c of the se
elected eleme
ent.
• replaceChild(newNode
e, existingNode), which replaces the existing child no
ode with the new
n node.
• replaceDatta(offset, len ngth, string), which replacees the text in a text node. T
The offset parrameter
specifies whhich characterr to begin with, length spe
ecifies how maany characterss to replace, aand string
specifies the
e text to inserrt.
o use these me
To ethods effectivvely and targe
et accurately where to add new nodes, yyou also need
d to move
aro
ound the document tree. Y
You can use th he following pproperties to n
navigate throu
ugh the DOM
M:
• lastChild, which
w returns the last child of a node.
• nextSibling
g, which returrns the node immediately ffollowing the current one.
• parentNod
de, which retu
urns the paren
nt node of a node.
Programming in HTML5 with JavaScript and CSS3 3-27
• previousSibling, which returns the node immediately prior to the current node.
Modifying a list
var list = document.getElementById("VenueList");
var newItem = document.createElement("li");
var newlist = document.createElement("ul");
list.AppendChild(newItem); // adds the new item to the end of the list
list.InsertBefore(newItem, list.childNodes.firstChild); // add the new item to the
beginning of the list
list.replaceChild(newlist, list.parentNode.firstChild); // replaces the old list
assuming it is the first child of its parent
Note: If you reinsert or reappend a node object into the document, it is automatically
removed from its current position.
The DOM also defines methods for removing nodes from the document tree, including:
document.removeChild(
document.geElementById("VenueList").firstChild
);
• removeAttribute(attributeName), which removes the named attribute from the element node.
• removeAttributeNode(node), which removes the given attribute node from the element.
To clear a text node rather than removing it completely, just set it to an empty string.
3-28 Introducction to JavaScript
Handling Ev
vents in the DOM
HTTML defines a number of evvents initiated d by the user aand the brow wser to which you
y can attach a
JavvaScript action. For examplle, when a use er moves the mouse
m over a help icon, the mouseoverr event
fire
es. When an e event fires, if you have set a listener forr the event, th
he browser willl run it. Manyy HTML
eleements provid de callbacks th hat you can use to capture the various e events that occcur and define code that
actts as a listener. These callbaacks typically have the namme oneventna ame where evventname is the name of
thee event. For example, you ccan handle the mouseoverr event for an n <img> elem ment by using the
onnmouseover ccallback, as fo ollows:
<img src=
="helpicon.g
gif" id="helpIcon" onmou
useover="win
ndow.alert('Some help te
ext');"
/>
Note: A callback is a re
eference to a ffunction that runs as the re
esult of anothe
er action
completing. In tthe case of an
n event handleer for an HTMML element, th he browser cauuses the
callback to run w
when it trigge
ers the correspponding even nt.
Yo
ou can also sett the event haandler as a pro
operty of the image displayying the help icon in the DOM, like
thiis:
document.
.image.helpI
Icon.onmouseo
over =
functio
on() { windo
ow.alert('Som
me help text
t'); };
Hoowever, this m
method only allows you to sset one listene
er on an event. The HTML D
DOM allows yyou to
dyynamically add
d and removee multiple event listeners fro
om elements in an HTML document
d by using the
folllowing methoods:
var helpI
Icon = docum
ment.getElementById("hel lpIcon");
helpIcon.
.addEventLis
stener("mouseover",
on() { windo
functio ow.alert('Some
e help text'); }}, false);
Programming in HTML5 with JavaScript and CSS3 3-29
Note: Keep the code in an event handler short and concise. Long-running event handlers
may impact the responsiveness of the browser.
Some events in the HTML DOM 'bubble', meaning that if the event occurs on an element (and it is or isn't
handled), the event will then also fire on the element's parent node and then on its grandparent node and
so on until the event reaches an element where it may not bubble any further or it reaches the root node.
Both addEventListener and removeEventListener have an optional third Boolean parameter indicating
whether or not this is the case.
Note: Note that Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 do not
support addEventListener() and removeEventListener(). Use the similar attachEvent() and
detachEvent() functions instead.
The following example shows how to bind a small script, which in this case copies the contents of a text
box to the screen, to the onClick event of a form button.
Lesson 3
Introd
duction
n to jQu
uery
jQuery is an opeen source Java aScript libraryy that deals wiith cross-browwser incompattibilities for yo
ou, leaving
you free to writee one piece oof code that ru uns on all browwsers. It proviides a lightwe
eight but pow werful
solution for sele
ecting, creatin
ng, and manip pulating eleme ents on a page, handling usser events in thet
bro
owser, and making AJAX ca alls to web services. It also has an active developmentt community w writing and
improving manyy plug-in scrip pts to provide e amazing effeects that you can use in you ur sites.
Miicrosoft active
ely contributes to jQuery an nd has include
es the jQuery library in new
w ASP.NET web site and
we
eb application n projects in V
Visual Studio.
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
• pabilities of jQ
List the cap Query.
T jQuerry Library
The
• Core. Thee jQuery core APIs enable yyou to mark ccode for execu ution once the
e page has fin
nished
loading, ccreate DOM elements,
e and loop through h a set of selected elementss.
• Events. jQ
Query enabless you to add script
s to and remove
r scriptt from event handlers
h in the
e browser,
such as mouseover,
m to
oggle, click, aand so on.
• Animatioon and Effectts. jQuery ena ables you to add a number of visual effects to elemen
nts on a page.
For example, fade in an
nd out, slide u
up, slide downn, and so on.
• Utilities. jQuery provid hods for workking with arrayys, strings, and other built--
des a numberr of extra meth
in JavaScrript objects.
jjQuery is a JavvaScript file th
hat you refere page with a script tag. You ccan download
ence in your p d it and
r
reference a lo
ocal copy in yo our page.
3-32 Introduction to JavaScript
Alternatively, you can reference its location on one of several Content Delivery Networks (CDNs), which
ensures faster downloads and caching in the browser.
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.min.js"
type="text/javascript"></script>
Note the protocol-relative URL which ensures that jQuery is downloaded by using the same protocol as
your page (http or https).
Most calls to the jQuery library ensure that the entire page has loaded in the browser before executing,
but it is still a good idea to add your own scripts to the end of the page. This example demonstrates the
most common way of doing this.
• ready() is an event that fires when the full DOM has been loaded by the browser
• The anonymous function contains the code that will run when the ready event is fired and the page
has been loaded.
Additional Reading: You can find the latest version of jQuery, full documentation and a
list of plug-ins available for use at http://go.microsoft.com/fwlink/?LinkID=267719.
Programming in HTTML5 with JavaScrippt and CSS3 3-33
3
D
Demonstr
ration: Ad
dding jQu
uery to a Web
W Proje
ect
D
Demonstra
ation Steps
A jQuery to
Add o a project byy using nuGet
1
1. On the W
Windows 8 Sta
art screen, clicck the Visual S
Studio 2012 tile.
2
2. In Visual Studio, on the
e File menu, p
point to New and then clicck Web Site.
3
3. In the Ne
ew Web Site d
dialog box, in
n the middle pane
p click ASP
P.NET Empty
y Web Site.
4
4. From the Web locatio
on list, click File System, se
et the file path
h to E:\Democode\jQuery
yDemoTest,
and then click OK.
5
5. On the Toools menu, po
oint to Libraryy Package Manager, and th
hen click Manaage NuGet Pa
ackages for
Solution.
6
6. In the Ma
anage NuGett Packages diialog box, clicck Online. A liist of available
e packages fo
or download
appears in order of popularity.
7
7. In the Sea
arch Online b
box, type jQuery.
8
8. In the listt of packages, click jQuery, and click Install.
9
9. In the Sellect Projects dialog box, click OK.
1 In the Ma
10. anage NuGett Packages diialog box, clicck Close.
1 In Solutio
11. on Explorer, no h been added to the projject and that it contains
otice that a Sccripts folder has
three filess.
3-34 Introduction to JavaScript
Note: The three files are the uncompressed jQuery library, a minified version for use on
production servers, and an IntelliSense file for Visual Studio to use.
1. In the Solution Explorer window, right-click the Scripts folder, point to Add, and then click
JavaScript File.
2. In the Specify Name for Item dialog box, type test, and then click OK.
3. Type the following code and notice that IntelliSense is unable to offer suggestions for statement
completion for jQuery functions.
$(document).ready(function () {
// your code here
});
4. In the Solution Explorer window, right-click the Scripts folder, point to Add, and then click
JavaScript File.
5. In the Specify Name for Item dialog box, type _references.js, and then click OK.
6. Add the following code to _references.js and then save it.
Note: If necessary, replace the jQuery version number (1.8.1) with that of the files
downloaded by the package manager.
7. In the _references.js file, type the following code and notice that IntelliSense is now able to offer
suggestions for statement completion for jQuery functions.
$(document).ready(function () {
// your code here
});
S
Selecting Elements and Traversing the
e DOM by
y Using jQ
Query
• Tag name
e. For example
e, $("h2")
• An attribu
ute on an elem
ment. For example, $("inpu
ut[type=text]"))
• Using pse
eudo-classes. For example, $("p:first")
After jQuery h
A has returned tthe set of seleected elementts, you can iterate through them, applyinng a filter as
r
required, and manipulate tthem in some way: Change their style, ad or change textt, and so on.
dd an event, o
I jQuery, the
In e functions thaat iterate thro
ough the set o
of elements are known as trraversal functiions. For
e
example, the each functionn iterates overr every selecte
ed element foor processing.
S
Selection traversal with the each funcction
<script typ
pe="text/jav
vascript">
$(docum
ment).ready(
(function () {
$("
"h2").each(f
function () {
this.style
e.color = "Red";
});
;
});
</script>
$("p").eq(7).css("color", "red
d");
3-36 Introduction to JavaScript
• each(function), which iterates over a set of selected elements and applies the given function to it.
$("p").each(function() {
this.css("color", "red");
});
• filter( expression ), which returns a subset of elements by applying the given filter over the original
set. The expression for the filter can be a tag name, CSS selector, or function.
$("p").filter( $(":first"));
• find(selectorString), which returns a subset of elements from those in your original set.
$("form").find("input.[type=text]");
• first() and last(), which return the first or last element in the original set.
• next() and prev(), which return the element immediately following or preceding the selected
element.
$("nav").next();
$("p").size();
• slice(int [, int]), which returns a subset of the original set starting at the given index through to the
end of the set. You can also pass a second argument to slice() which denotes an end index.
$("p").slice(4);
Additional Reading: You can find a full list of traversal and filtering functions at
http://go.microsoft.com/fwlink/?LinkID=267720.
Programming in HTTML5 with JavaScrippt and CSS3 3-37
7
A
Adding, R
Removing,, and Mod
difying Ele
ements by
y Using jQ
Query
$("p").addClass("strike");
$("ul")
).append("<li>The new la
ast list ite
em</li>");
$("#War
rning").detach();
• html( htm
mlString ), which gets and
d sets the HTM
ML content of the first elem
ment in the sett.
$("h1")
).html("<hgroup><h1>New Heading</h1
1></hgroup>");
• replaceW
With( htmlStrring), which re
eplaces each e
element in the set with the
e given HTML..
$("#War
rning").replaceWith("<p>
>Panic Over!</p>");
$("inpu
ut[type=text]").val();
Most of these
M e functions apply to each ellement in the set of elemen nts retrieved b
by your selecttor. However,
s
several apply only to the firrst element in
n the set, inclu
uding attr(), ccss(), height()), html(), val((), and
w
width().
3-38 Introduction to JavaScript
H
Handling Control Events
E by Using jQu
uery
jjQuery enablees you to add and remove JJavaScript codde for event h
handlers in the
e browser. You can write
t JavaScriptt code for these handlers either in the HT
the TML page or in separate sccript files and then bind
t
them to the e
event. You bin
nd a handler fu
unction to an event by usinng the jQueryy bind method d. This
m
method takess two parametters:
• The name
e of the eventt being handle
ed.
$("#subbmit").bind("click", fun
nction() {
// co
ode for click event hand
dler for the
e submit button
};
jjQuery define
es a shortcut m
method for all the common
n DOM eventss, such as click
k() shown in tthe next
e
example.
The following example sho
T ows how to bin t case repeats the contents of a text
nd a small scrript, which in this
b out to the
box e screen, to th
he onClick evvent of a form's submit buttton.
B
Binding an action to an e
event by usin
ng jQuery
<!DOCTYPE hhtml>
<html xmlnss="http://ww
ww.w3.org/1999/xhtml">
<head>
<meta ccharset="utf
f-8" />
<title>>Binding eve
ents with JQuery</title>
>
<scriptt type="text
t/javascript" src="Scrip
pts/jquery-1
1.8.0.js"></script>
</head>
<body>
<form>
<p>><label>Writ
te Your Name: <input typ
pe="text" id
d="NameBox" /></label></
/p>
<innput type="b
button" id="submit" valu
ue="Click to
o submit" />
</form>>
<div idd="thankYouA
Area"></div>
<script typpe="text/jav
vascript">
$(documment).ready(
(function () {
$(""#submit").c
click(
3-40 Introduction to JavaScript
function () {
var userName = $("#NameBox").val();
$("#thankYouArea").replaceWith("<p>Thank you " + userName + "</p>");
})
});
</script>
</body>
</html>
The following list summarizes some of the shortcut methods that you can use to bind events to elements:
• click(), dblclick() : Binds to mouse click events.
• error() : Binds to occurrence of errors in the document such as broken links and missing images.
• load(), unload() : Binds to events triggered when a specified element is loaded or unloaded on the
page.
Lab: Displayying Da
ata and Handling Eve
ents by Using
Script.
JavaS
S
Scenario
The conferencce being orgaanized by Con
T ntosoConf connsists of a num
mber of sessio
ons that are orrganized into
t
tracks. A trackk groups sessions of related
d technologies, and confere ence attendee
es can view thhe sessions in
a track to deteermine whichh ones may be e of most interest to them.
To assist confe
T erence attend dees, you have
e been asked to create a Scchedule page for the Conto
osoConf
w
website listing
g the tracks an
nd sessions fo
or the conference.
O
Objectives
A
After y will be able to:
completting this lab, you
• Handle th
he events thatt can occur when a user intteracts with a page by using
g JavaScript.
E
Estimated Tim
me: 60 minutes
• User Nam
me: Student
• Password
d: Pa$$w0rd
3-42 Introduction to JavaScript
First, you will use the HTML5 DOM to obtain a reference to the page’s schedule list element. Then you will
implement a function that creates list items (one list item for each session). Information about the sessions
is stored in a file in JSON format. You will implement a function that reads this data and adds the details
of each session to the list element. Finally, you will run the application and view the Schedule page to
verify that it correctly displays the list of sessions.
2. Write code to get the schedule list element on the Schedule page
3. Implement the createSessionElement function that creates the list item for a session
4. Implement the displaySchedule function that adds session items to the list for display
2. Start the 20480A-SEA-DEV11-03 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 1
folder.
4. In the ContosoConf project, review the content of the page schedule.htm. Notice that the schedule
page section, which will be used to display the list of sessions, currently contains an empty list, also
named schedule.
5. Also notice that the schedule.htm page references the JavaScript code in the
scripts\pages\schedule.js script file.
6. Review the scripts\pages\schedule.js script file. This file contains the details of each session held in
JSON format. The data is held in an array named schedule, and each object in the array has three
properties that specify the session id, the session title, and the tracks to which the session belongs (a
session may be part of more than one track).
X Task 2: Write code to get the schedule list element on the Schedule page
1. In the schedule.js file, find the comment TODO: Task 2
2. Write JavaScript code to get the schedule list element from the DOM and assign it to a variable
named list. You will use this variable to display the details of each session in the list on the Schedule
page.
X Task 3: Implement the createSessionElement function that creates the list item for a
session
1. In the schedule.js file, find the comment TODO: Task 3. This comment is located in the
createSessionElement function, which looks like this:
function createSessionElement(session) {
...
};
Programming in HTML5 with JavaScript and CSS3 3-43
2. The purpose of this function is to create a list element containing the name of the session passed in
as the parameter.
3. Add JavaScript code to create a <li> element, set its text content to the session title, and then return
this element.
X Task 4: Implement the displaySchedule function that adds session items to the list
for display
1. In the schedule.js file, find the TODO: Task 4 comment. This comment is located in the
displaySchedule function, which looks like this:
function displaySchedule () {
clearList();
...
};
2. The purpose of this function is to display the title of each session in the list on the Schedule page.
3. Add JavaScript code to iterate over the schedule array using a for loop, create a session object for
each item in the array, and add the title of the session to the list element on the Schedule page.
4. The list is available in the list variable, and you can use the createSessionElement function to create
a list item for each session.
X Task 5: Run the web application and view the Schedule page
1. Run the application and view the schedule.htm page to verify that the list of sessions is displayed.
3-44 Introducction to JavaScript
The Schedule pa
age should lo
ook like this:
Note: Rem member that yyou can use the F12 Develo oper Tools in Internet Exploorer to debugg
your applicationn. Also, if you make any cha anges to yourr code, make ssure to clear tthe browser
cacche before running the app plication again (press CTRLL+R in the F122 Developer Tools window).
Ottherwise, Interrnet Explorer may attempt to run the pre evious version
n of your JavaaScript code.
Re
esults: After coompleting thiis exercise, you will have ad
dded a Schedu
ule page to th
he ContosoCo
onf
ap
pplication thatt displays the details of con
nference sessio
ons.
Programming in HTML5 with JavaScript and CSS3 3-45
First, you will add two checkbox HTML elements to the Schedule page; the first will enable the user to
specify that the sessions for track 1 should be listed, and the second will enable the user to specify that
the sessions for track 2 should be listed (if both checkboxes are checked, then the sessions for track 1 and
track 2 will both be listed). Then you will add JavaScript code to handle the click events of these
checkboxes; you will update the displaySchedule function to show only sessions that are in the tracks
currently selected by the checkboxes. Finally, you will run the application and view the Schedule page to
verify that selecting and deselecting the checkboxes correctly updates the session list.
4. Update the displaySchedule function to display the sessions for selected tracks
2. In the schedule.htm file, before the schedule list, add two checkboxes with labels for track 1 and
track 2.
X Task 2: Write code to get the checkbox elements from the Schedule page
1. In the scripts\pages folder, open the schedule.js file.
2. After the list variable is defined, add two variables named track1Checkbox and track2Checkbox
3. Add JavaScript code to get the checkbox elements show-track-1 and show-track-2 from the DOM
and reference them in these variables.
X Task 4: Update the displaySchedule function to display the sessions for selected
tracks
1. Modify the displaySchedule function to add sessions to the list only when they are in the currently
selected tracks (one track, both tracks, or neither track might be selected).
X Task 5: Run the web application and view the Schedule page
1. Run the application and view the schedule.htm page.
2. Verify that if both checkboxes are selected all tracks are listed.
3. Verify that if only Track 1 or Track 2 is selected, only the sessions for that track appear.
• Registration
• Lunch
• Getting to Grips with JavaScript
• Registration
Results: After completing this exercise, you will have updated the Schedule page to filter sessions based
on which tracks have been selected.
Programming in HTTML5 with JavaScrippt and CSS3 3-47
7
Module Rev
view an
nd Take
eaways
M
Module Rev
view
IIn this modulee, you have le
earned how to o use JavaScrip pt code to add dynamic functionality to a website.
Y have seen
You n how to write e JavaScript code to perforrm common operations
o succh as selecting
g and
m
modifying the
e data displayyed on a page e, and respond ding to eventss triggered byy a user viewin ng the page.
Y have also
You o seen how to use the jQue ery library to simplify the co
ode required tto process the e contents of
a page, and to
o make this co ode portable so that it will function corrrectly in different web brow wsers.
V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.
Statement Answer
Question
n: What is the purpose of th
he DOM?
T
Test Your Kno
owledge
Question
load
ded
available
read
dy
3-48 Introduction to JavaScript
Question
bind
4-1
Module 4
Creating Forms to Collect and Validate User Input
Contents:
Module Overview 4-2
Modu
ule Ove
erview
Ob
bjectives
Aftter completing this module
e, you will be able to:
• ut forms by ussing HTML5.
Create inpu
• Use HTML5
5 form attributtes to validate
e data.
Lesson 1
Creatting HT
TML5 F
Forms
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Use the H
HTML5 <form nd specify its common attributes.
m> element an
• Explain ho
ow to use the
e new HTML5 input types.
A typical
t HTML5
5 form looks llike this:
An
n HTML5 Forrm
<
<form name="uuserLogin" m
method="post
t" action="lo
ogin.aspx">
<fieldset>
<legend>EEnter your l
log in details:</legend>
>
<div id="usernameFieeld" class="field">
<input id="uname" name="usernname" type="t
text" placeh
holder="Firs
st and Last N
Name" />
<label for="uname"">User's Nam
me:</label>
</div>
<div id="passwordFieeld" class="field">
<input id="pwd" naame="passwor
rd" type="pas
ssword" plac
ceholder="Pa
assword" />
<label for="pwd">UUser's Passw
word:</label>
>
</div>
</fieldset>>
<input typee="submit" v
value="Send" />
<
</form>
• The action performed w when the user submits the fo orm to the server. This is a URL to which
h the form
will be sent. If you omit tthe URL, the form
f is sent to
o the current U
URL of the we eb page.
• The metho od to be used to send the ddata. When submitting dataa to the serverr by using a fo
orm, this
attribute sh
hould normallyy be set to po
ost.
A form
f containss one or more e input fields e
enclosed in a <fieldset> ellement. You use u this eleme ent to draw
abbox around th he set of fieldss, and add a la
abel to the set by using the
e <legend> element.
e The < <fieldset>
ele
ement is optioonal, but it cann be very usefful on larger fforms, where it is helpful to
o the user to ssee labeled
secctions.
Wiithin the <fieldset> eleme ent, you add a <div> eleme ent for each ffield in the forrm, adding cla
ass="field"
as an attribute. CSS can use the
t class to styyle the form. A
Adding a div element gives you a place to state
Programming in HTML5 with JavaScript and CSS3 4-5
the intention of the input element by adding an id attribute. Additionally, the div element serves as a
container for the HTML5 elements necessary to receive the input, its validation, and its label.
Within the <div> element, you add an <input> element to collect the data. An input element should
contain the following attributes:
• An id and name attribute. The id attribute is typically used by CSS to style the field and JavaScript
code that control the field in the browser; the name attribute is used by the server to reference fields
on the form when it is submitted.
• A type attribute. This attribute specifies the type of the input. The browser uses the type attribute to
create a visual control suitable for the data-type required. This is covered in greater detail in the next
topic.
• A placeholder attribute. The placeholder appears on the control as a prompt to help the user know
what to type.
Most input elements have an associated <label> element. This provides a way to label the input on the
form. The for attribute indicates the input fields associated with the label. Note that the value of the for
attribute should match the id attribute of the input element, not its name.
Finally, you need to provide a way to post the data to the server for processing; this is the purpose of the
<input> element with the data type submit. This markup creates a clickable control that sends the data
in the form to the server.
4-6 Creating Forms to Collect and Validate User Input
HT
TML5 Inp
put Types aand Eleme
ents
HT
TML5 provides you with a w
wide range off input types for forms.
To
o change the ttype of data yyou wish to coollect, specify tthe type attribute of the <input> element,
prooviding one oof the following values: button, checkb box, color, date, datetime,, datetime-lo ocal, email,
file
e, hidden, im
mage, month, number, passsword, radio o, range, reseet, search, sub
bmit, tel, textt, time, url,
or week. Note tthat not all these types are not yet fully aadopted or evven implemen nted by most browsers.
They are design here they are not implemented.
ned to fail bacck to harmlesss text fields wh
Yo
ou can use a <<datalist> ele
ement with text input to prrovide autocomplete option ns. Note that you do not
eed to specify the input type, you simplyy indicate that the input is a list and provvide the possib
ne ble options
byy using the datalist elemen
nt, as follows:
<input id
d="ageCatego
ory" name="ag
geCategory" list="ageRa
anges" />
<datalist
t id="ageRan
nges">
<option
n value="Und
der twos">
<option
n value="2 - 7">
<option
n value="8 - 12">
<option
n value="13-
-17">
<option
n value="Adu
ult">
</datalis
st>
The <select> element is a container for a number of fixed <option> elements, which predefine inputs
the user is allowed to give. This saves the user from typing common data, where the options are well
understood and can be defined at design time. To group options into smaller logical lists, you use the
<optgroup> element. This will help the user make sense of a longer list. You define a select element like
this:
HT
TML5 Inp
put Attribu
utes
Some attributess are independ dent of the input type. For example, a co
ommon requirement is to p place the
cursor in the firsst field of the form when thhe page loadss. You can achhieve this by setting the new
w
au
utofocus attrib bute on the control.
In the following
g example, the
e email addresss field receive
es the focus when
w the form he email
m loads, and th
address is comppleted automaatically if the u
user has typed
d it in before.
<form id=
="loginForm"
" action="log
gin.aspx" me
ethod="post"
" autocomplete="on">
Email: <input name
e="email" type="email" p
placeholder=
="Email address"
autofocus
s="autofocus
s"/>
Passwor
rd: <input n
name="password" type="pa
assword" aut
tocomplete="o
off" />
<input type="submit" />
</form>
The placeholde
er attribute pu
uts temporaryy content in a text field to p
prompt the usser to enter daata.
Programming in HTML5 with JavaScrript and CSS3 4-9
9
Lesson 2
Valid
dating U
User Inp
put by Using H
HTML5
5 Attributes
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain th of client-side fforms validatiion.
he principles o
• Add form t ensure thatt mandatory fiields are not left empty.
ms validation to
• Validate n
numeric inputt.
• Validate ttext input.
• Style field
ds to highlightt input requirrements.
4-10 Creatingg Forms to Collect aand Validate User Innput
Prrinciples o
of Validatiion
Whhen you creatte a form and add it to a w website, the daata it collects w
will vary in terrms of qualityy and
acccuracy. In factt, forms are w
wide open to collect
c anythin
ng the user types in, whether it is valid o or not. User
inp
put may even be malicious,, designed to probe how yo our applicatioon reacts to un nexpected data.
Vaalidation is the
e process of checking the ddata for obvious errors, so tthat when it iss eventually handled at
thee server, there
e are as few errors as possib
ble.
E
Ensuring t
that Fields are Not Empty
Wiith HTML5, yo nd lower limitts of numeric input. The folllowing code shows an
ou can control the upper an
exaample:
<input id
d="percentag
ge" type="num
mber" max="1
100" min="0"
" />
e number inp
Note: The put type also ssupports other attributes su uch as step, w
which specifiess
valid incrementss for numeric values entereed in a field. T
These attribute
es are not currrently
implemented in n Internet Explorer 10.
Programming in HTTML5 with JavaScrippt and CSS3 4-13
3
V
Validating
g Text Inp
put
HTML5 provid
H des input typees such as tel and email thaat expect data
a in a specific format, but yo ou can also
a
apply wn custom rules to many in
your ow nput fields by using a regular expression. For example e, if you
r
require an ord
der reference to comply with the pattern n 99XXX, where 9 is any diggit and X is anny uppercase
l
letter, use the
e HTML5 patte ern attribute to specify a re
egular expression to validate the field. YYou can
p
provide feedb
back to the usser about the expected form mat of the datta by using th
he title attribu
ute.
IIt is easy to geet too comple ex with regulaar expressions,, so use patte
ern for simple
e pattern recognition.
E
Expressing a ccomprehensivve password ru ules base as a single regulaar expression will
w take time and
e
extensive testing to get right, and a proggrammatic so olution construucted by usingg JavaScript m
may produce
a more efficie ent and maintaainable solution.
4-14 Creatingg Forms to Collect aand Validate User Innput
To
o help the user identify the fields they mu ust complete, you should in ndicate visually whether th hey are
req
quired or not required. Onee way to do th his is by markking each requ
uired field witth a text asteriisk in the
forrm design. In this example, the asterisk is styled red by using inline
e CSS:
<form id=="registerFo
orm" method="post" actio
on="registra
ation.aspx">
<div idd="firstName
eField" class="field">
<labeel for="firs
stName">First name:</lab
bel>
<inpuut id="first
tName" name="firstName" required="r
required" placeholder="Y
Your
first namme" />
<spann style="color:red">*</span>
</div>
...
</form>
A better
b way to indicate that a field is requ
uired is to use
e CSS to style tthe field acco ording to the rrequired
atttribute. You caan create the following styles in a stylesh
heet. The firstt rule specifiess that all inputt elements
aree surrounded by grey bord der, the secondd rule specifiees that if the required
r attribute is set, the border
color is orange.
input{
border:
: solid 1px #888;
}
input:req
quired
{
border-
-color: #8a0
0;
}
input{
border: solid 1px;
}
input:invalid {
border-color: #f00;
}
input:valid {
border-color: #0f0;
}
4-16 Creatingg Forms to Collect aand Validate User Innput
Lesson 3
Valida
ating User Inp
put by U
Using Ja
avaScript
HT
TML5 forms in nput types and d attributes are useful for pperforming sim
mple field-by--field validatio
on of data.
Ho
owever, for mo ore complex types
t ence fields as part of the
of validaation, or wherre you need to cross-refere
validation proce
ess, you may n need to revertt to using JavaaScript code. This lesson de
escribes how yyou can
use
e forms eventts to validate d
data and provvide feedbackk by using JavaScript.
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
• Perform additional checkks to verify that mandatoryy fields are not empty.
• namic feedbacck on validation errors.
Provide dyn
Programming in HTTML5 with JavaScrippt and CSS3 4-17
7
H
Handling Input Eve
ents
The following code example shows a forrm that runs tthe validateFo
T orm method when the useer submits the
e
d
data. The onssubmit attribu
ute of the form
m specifies the JavaScript code
c to run when the subm
mit event
o
occurs:
<form id="registrationForm" me
ethod="post"
" action="registration.a
aspx"
onsubmit="return validateForm(
();" >
...
<inpu
ut type="submit" />
</form>
>
functio
on checkAge() {
// Va
alidate ageInput.value a
and confirm that the user has speci
ified a vali
id age
(>=18, <= 120)
var ageValid
a = ...;
if (!ageValid) {
4-18 Creating Forms to Collect and Validate User Input
In this example, the validation logic (not shown) verifies that the user enters a value between 18 and 120
in the confirm-age field. If this is not the case, the setCustomValidity function displays a custom error
message and prevents the data from being submitted. If the data is valid, passing the empty string to the
setCustomValidity function resets the error handling and the data can be submitted.
This type of validation is very fine-grained, and the input event runs each time the user enters a character
in the input field, so do not use this approach to implement time-consuming validation that may cause
the web page to slow down.
Note: You can also use the oninput attribute of an input field to catch the input event,
rather than using the addEventListener function.
Programming in HTTML5 with JavaScrippt and CSS3 4-19
9
V
Validating
g Input
functio
on isAnInteger( text ){
var intTestRe
egex = /^\s*(\\+|-)?\d+\s*$//;
retur
rn String(text).search(i
intTestRegex
x) != -1;
}
functio
on validateForm()
{
if( ! isAnInteger(document.g
getElementBy
yId('score').value))
ret
turn false; /* No, it’s not a num
mber! Form validation fa
ails */
retur
rn true;
}
4-20 Creatingg Forms to Collect aand Validate User Innput
En
nsuring th
hat Fields are Not Empty
The HTML5 req quired attributte verifies thaat a user enterrs something iinto a field, buut this data caan be
spaaces, tabs, and
d other white
espace charactters. To ensure e that a field actually contaains non-whitespace
data, you can ad dd JavaScript code that use es a regular exxpression to check
c the valu
ue that the use er has
entered. In the following
f example, the regular expressio on matches on ne or more grroups of signifficant
characters.
<form id=="scoreForm"
" method="post" action=""..." onsub
bmit="return validateFor
rm();" >
...
<div idd="penalties
sField" class="field" >
<inpuut id="penalties" name="penalties" type="text"
" />
<labeel for="pena
alties">Penalties:</labeel>
</div>
...
</form>
function isSignifica
ant( text ){
var notWhitesp
paceTestRege
ex = /[^\s]{1,}//;
return String(text
t).search(notWhiteSpaceTTestRegex) != -1;
}
function validateFor
rm() {
if( ! i
isSignifican
nt(document.ggetElementBy
yId(‘penalties’).value))
retur
rn false; /* No! Form validation fails */
return true;
}
Programming in HTTML5 with JavaScrippt and CSS3 4-21
1
P
Providing
g Feedback
k to the U
User
As when using
A g HTML5 inpu ut types and aattributes, if a form is not su
ubmitted, it iss helpful to prrovide the
u
user with a vissual indication
n of the error.. You can achieve this type of feedback p programmaticcally, by
u
using a combination of CSSS and JavaScript code that dynamically cchanges the cclass of a field depending
o whether th
on he contents arre valid or nott valid.
.valida
atedFine {
borde
er-color: #0f0;
}
.valida
ationError {
border-
-color: #f00;
}
functio
on validateForm() {
var textbox
t = document.getEl
lementById("
"penalties");
if( ! isSignificant(textBox.value)) {
tex
xtbox.className = "validdationError"
";
ret
turn false; /* No! For
rm validatio
on fails */
}
textb
box.className = "validattedFine";
retur
rn true;
}
Note: In
nternet Explorrer 10 styles fiields that fail validation in a similar manner, but the
ttechnique sho
own makes the styling conssistent for use ers running other browsers.
4-22 Creatingg Forms to Collect aand Validate User Innput
Lab: C
Creating
g a Form
m and Validat
V ting Use
er Inpu
ut
Sccenario
Deelegates who w
want to attend ContosoConf will be required to register and provid
de their details. You
have been askedd to add a page to the Con
ntosoConf website that impplements an attendee
a regisstration
forrm.
The server-side code already exists to proccess the attendee data. How wever, the reg
gistration pagge performs
very minimal vaalidation that is not user frie
endly. You have decided too add client-siide validation to the
forrm to improvee the accuracyy of the registtration data entered by atte
endees and too provide a be etter user
experience.
Ob
bjectives
Aftter completing this lab, you
u will be able to:
You will select the correct input types for each piece of data collected by the form. Then you will enhance
the input with additional attributes to improve the user experience and to add validation. For example,
the first input item should automatically receive the focus when a page loads. Also, most of the input
items are mandatory, the password must be sufficiently complex to improve security, and the form must
prevent incomplete data or data that is not valid from being submitted. Finally, you will run the
application, view the Register page, and verify that form validation performs correctly.
2. Start the 20480A-SEA-DEV11-04 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 1
folder.
4. Open the register.htm file.
5. Find the <form> element and read the TODO comment that describes the form input requirements
together with an HTML snippet to use as a template.
6. Also notice that register.htm has a reference to the style sheet /styles/pages/register.css in the
<head> element, and a reference to the JavaScript file /scripts/pages/register.js just before the
</body> tag. The CSS file contains the styles for the registration page, and the JavaScript file
contains the code used by the registration page.
• Use the <div class="field"> template when creating the form inputs; provide a label for each input,
and remove this template when you have added all of the inputs.
2. Run the application, view the register.htm page, and test the form with some valid data. The
following image shows some suggested valid data values that you can use (use the text Passw0rd for
the password).
4-24 Creatingg Forms to Collect aand Validate User Innput
The Registe
er page should
d look like this:
3. After you have entered a complete set of valid dataa, click Registter. Verify that the Thanks for
registering
g page appears.
4. Return to th
he Register p page. Notice that you have to explicitly click
c to put the
e cursor in the
e First
name field to start registtering anotherr attendee.
6. Close Intern
net Explorer.
X Task 4: Ch
heck for Misssing Mand
datory Data
1. In the regisster.htm file, add required
d attributes to
o the mandato
ory form inputts (FirstName
e,
LastName, EmailAddresss, Password, ConfirmPasssword).
Programming in HTTML5 with JavaScrippt and CSS3 4-25
5
2
2. Run the aapplication, view the registter.htm page,, and verify th
hat the form cannot
c be sub
bmitted if any
of the maandatory fields are empty.
X Task 5: Add
A Passwo
ord Comple
exity Validattion
1
1. In the reg
gister.htm file
e, modify the Password input to ensure
e that the ente
ered value is aat least five
letters and numbers.
• Use the fo
ollowing regu
ular expression
n:
[a-zA-Z0
0-9]{5,}
At least
t 5 letters and numbers
2
2. Run the aapplication, view the registter.htm page,, register as an attendee, an
nd verify that Password
input disp
plays the error message forr password en
ntries that are not valid.
3
3. Verify thaat valid passw
words containing at least fivve letters and numbers are sstill accepted..
4-26 Creating Forms to Collect and Validate User Input
Results: After completing this exercise, you will have modified the attendee registration page to validate
the data entered by attendees.
You will implement a function to compare the two passwords and display an error message when the
passwords do not match. Then you will add input event listeners for the password inputs, which call the
password comparison function. You will test this feature to ensure that a user cannot submit a form with
mismatching passwords.
Next, you will add a CSS style to highlight input elements that are not valid (some browsers such as
Internet Explorer already highlight them with a red border, but other browsers might not implement this
feature by default). You will run the application, view the Register page, and verify that elements that are
not valid are highlighted.
4. Add Input Event Listeners to the Inputs to Call the checkPasswords Method
X Task 1: Write Code to Get the Contents of the Password Input Elements
1. In Visual Studio, open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.
This project contains a working version of the application as it should appear at the end of exercise 1,
together with additional comments and code fragments that are used by this exercise.
2. In the ContosoConf project, open the scripts\pages\register.js file and find the following comment:
// TODO: Task 1 - Get the password <input> elements from the DOM by ID
3. Create variables named passwordInput and confirmPasswordInput that contain references to the
password elements.
Note: The id attributes of the <input> elements are password and confirm-password.
X Task 3: Write Code to Display a Custom Error Message if the Passwords Differ
1. In the comparePasswords function, use the setCustomValidity method of the confirm-password
input element to display an error message when the confirm-password input does not match the
password input. If the passwords match, clear the error message.
Note: Setting a non-empty custom validity message will prevent the form from being
submitted.
X Task 4: Add Input Event Listeners to the Inputs to Call the checkPasswords Method
1. The password input elements raise an event named input when text is entered. In the
addPasswordInputEventListeners function, add event listeners for this event to call the
checkPasswords function.
2. Run the application, view the register.htm page, and verify that an error message is displayed when
the data in the Confirm Password box does not match the data in the Password box.
3. Also verify that the message does not appear if the passwords are the same.
4. Close Internet Explorer.
2. At end of the file, add a CSS rule that changes the background color of input elements that are not
valid to #f9b2b2.
3. Internet Explorer automatically adds a red outline to inputs that are not valid. Remove this default
styling by setting the outline CSS property to none. Ensure that the CSS rule only applies when the
<form> element has the submission-attempted class.
Note: The extra CSS class is added by the formSubmissionAttempted function, which is
called when the Register button is clicked, as shown in the following code from the register.js
file:
var formSubmissionAttempted = function() {
form.classList.add("submission-attempted");
};
var addSubmitClickEventListener = function() {
submitButton.addEventListener("click", formSubmissionAttempted, false);
};
Initially, the required form inputs are empty and therefore not valid. However, the application
should allow the user to complete the form before showing error messages.
4. Run the application, view the register.htm page, click the Register button without entering any
registration details, and verify that inputs that are not valid are highlighted with colored backgrounds.
4-28 Creatingg Forms to Collect aand Validate User Innput
The Registe
er page should
d look like this if you attem
mpt to registerr without provviding any dettails:
Reesults: After co
ompleting thiis exercise, you will have modified the re
egistration pag
ge to validate
e password
inp
puts.
Programming in HTTML5 with JavaScrippt and CSS3 4-29
9
Module Rev
view an
nd Take
eaways
M
Module Rev
view
IIn this module e, you have le
earned how to o create HTMLL5 forms that enable a userr to enter dataa and to sendd
i to a server ffor processing
it g. You have seeen how to usse the HTML5 input types anda attributes to specify
t type of eaach input field
the d and to valida
ate the data e
entered by the
e user in the bbrowser beforre it is
s
submitted. Yo
ou have also seen how to provide feedbaack to the use er by styling in
nput that is no
ot valid and
d
displaying me eaningful erroor messages.
IIn addition, yo
ou have learned how to use
e JavaScript code to implem
ment more co
omplex forms validation
a styling.
and
V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.
Statement Answer
If you define a field with an HTML5 input type that is not supporrted by the
user's browser, the field ddoes not appe
ear on the forrm when the b
browser
displays it. T
True or False??
V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.
Statement Answer
Module 5
Communicating with a Remote Server
Contents:
Module Overview 5-2
Lesson 1: Sending and Receiving Data by Using the XMLHttpRequest Object 5-3
Lesson 2: Sending and Receiving Data by Using the jQuery Library 5-13
Lab: Communicating with a Remote Data Source 5-19
Modu
ule Ove
erview
Ma any web applications require the use of data held by a remote site. In some case es, you can acccess this
data simply by d downloading it from a speccified URL, buut in other casses the data is encapsulated d by the
remmote site and made accesssible through a web service e. In this moduule, you will le
earn how to acccess a web
serrvice by using
g JavaScript co
ode and to inccorporate remmote data into o your web ap pplications. Yo
ou will look
at two technolo ogies for achie
eving this: the XMLHttpRequest object, which acts ass a programm matic
wrrapper around d HTTP requessts to remote web sites, and d the jQuery library, which simplifies ma any of the
tassks involved in
n sending requests and recceiving data.
Ob
bjectives
Aftter completing this module
e, you will be able to:
• Send data tto a web service and receivve data from a web service by using an X
XMLHttpRequ
uest object.
• Send data tto a web service and receivve data from a web service by using the jjQuery libraryy.
Programming in HTML5 with JavaScrript and CSS3 5-3
3
Lesson 1
Send
ding and
d Receiiving D
Data by Using tthe
XMLHttpReequest O
Object
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain ho
ow a browserr uses HTTP GET requests to
o retrieve rem
mote data.
• Explain ho
ow to use the
e XMLHttpRe
equest object to send a req
quest to a rem
mote server.
• Handle th
he data return
ned by a serve
er in response
e to a request..
• Process th
he received data asynchron
nously.
How a Brow
wser Retrieves Web
b Pages
Wh hen you type a URL in the address bar o of your web brrowser, it initiates an HTTP GET operatio
on to
rettrieve the HTM ML structure ffor the web pa age from the web server. T The web browser receives thhis
strructure and pa arses it to creaate the documment object mmodel (DOM), which it then n renders. The
ppropriate CSSS rules for the web page wiill be applied, and any JavaScript code linked to the p
ap page will be
run n. At this poin
nt, the page iss ready for the
e user to view
w.
Wh hile the browsser is processiing the DOM structure for a page, if it en ncounters ele ements with a src
pecify the URLL of an external resource (such as a file), it initiates furrther HTTP GE
atttribute that sp ET
opperations to do ownload each h of these resoources in turn
n, and then loaads them as child objects in n the DOM.
This process can n take some tiime, especiallyy if the resourrces are refere
ences to large e files. Many d
developers
usee JavaScript code to set the e src attribute
e of an elemen nt dynamically, after the paage has loade ed, enabling
ind
dividual resou urces to be loaaded on demaand while the page is running. This operration can also o trigger an
HTTTP GET operaation.
Altthough this mmechanism cou o retrieve data on demand, there are on
uld be used to nly three HTML elements
tha <image>, <ifframe>, and <script>, and
at provide a ssrc attribute, < ended to import,
d they are inte
resspectively, graaphics, HTML fragments, an nd JavaScript code. None o
of these elemeents is ideally suited to
any other type o of data.
Programming in HTML5 with JavaScrript and CSS3 5-5
5
U
Using the
e XMLHttp
pRequest Object
O to Access Re
emote Daata
To handle mo
T ore generic reqquests, HTMLL5 provides the XMLHttpRequest objecct. This object is specifically
d
designed to lo
oad data into the DOM on demand. Nott only can it trrigger HTTP GET G operation ns, it can also
i
invoke POST and HEAD re equests. The XXMLHttpRequ uest object caan return text and XML datta, and tracks
t status of H
the HTTP operatioons so that yo ou can perform
m any approp priate error checking. Additionally, it can
b used synch
be hronously or aasynchronously. It is supported in all majjor browsers, so the XMLHHttpRequest
o
object is the oobject of choice for retrieving data by ussing HTTP me ethods from within
w a web p
page.
The XMLHttp
T pRequest object provides a means to acccess any type e of remote daata; you are not restricted
t data for ele
to ements that p ommon use is to call a web service, passiing it data
provide a src aattribute. A co
e
entered by the user on a fo
orm, and thenn processing th he response that is returne
ed.
IIn browsers th
hat support HTML5, you usse the followin
ng JavaScript code to create an XMLHtttpRequest
o
object:
var req
quest = new X
XMLHttpReque
est();
The open() m
T method define es the HTTP mmethod and th he url for this request.
r The H
HTTP method can be set too
e
either GET, PO OST, or HEAD D. You use GEET to request a known resource without parameters, w while you use
P
POST to sendd parameterize ed data to thee server, mostt commonly fo orm data, to b
be parsed as p
part of the
r
request. HEAD D specifies that the response should only be header information, aand can be use eful, for
e
example, to get a summaryy of a large reesource aheadd of actually downloading itt.
To transmit th
T he request, call the send() method. Note
e that the bro
owser automattically handless the sending
o any cookies associated with
of w the domaain, based on the value of tthe URL.
Calls to the se
C end() method d are asynchroonous by defa
ault, meaning that your JavvaScript code w
will not blockk
t wait for a rresponse. If yo
to ou require a re
esponse beforre continuing, you can makke the currentt thread of
5-6 Communicating with a Remote Server
execution stop and wait for a response. To do this, use the optional third argument of the open() method
as follows:
H
Handling HTTP Erro
ors
You should ch
Y heck the outcoome of the seend() functionn to verify tha
at the request has actually been
b sent. To
d this, examiine the statuss property of the request o
do object. This prooperty contains the HTTP sstatus code off
t send operration. A statu
the us code of 2000 indicates succcess; other co
odes indicate some kind off error or
w
warning. For e
example, a staatus code of 404
4 indicates tthat the resou urce being req
quested couldd not be
f
found. The sta
atusText property provide es more informmation in the form of a textt message.
functio
on tryMyLuck() {
var
r request = new XMLHttpR
Request();
req
quest.open("GET", "/luck
kydip/enter"
");
req
quest.setRequestHeader("
"User-Agent"
", "XMLHttpRequest");
req
quest.send();
...
if (request.status != 200)
) {
alert("Error " + reque
est.status + " - " + request.status
sText);
}
...
}
Additio
onal Reading: For more infformation abo out the differe
ent HTTP statu
us codes that can
occur, and the
o eir meaning, ssee http://go.microsoft.com
m/fwlink/?LinkkID=267722.
You should w
Y wrap your code e in a JavaScriipt try…catch
h block to han
ndle any other unexpected exceptions
c
caused by nettwork or communications ffailure in the bbrowser; netw
works are noto
oriously unreliiable and
f
failures can occcur at any tim
me.
try {
} catch (exception) {
/* Handle any exceptions here. This example displays the exception to the user */
alert(exception);
The catch block looks a little like a function definition; it takes a parameter that is populated with
the details of the exception that has occurred. The actual contents of this parameter will depend
on the specific error that triggered the exception.
Programming in HTML5 with JavaScrript and CSS3 5-9
9
C
Consumin
ng the Ressponse
JJust as the boody parameterr passed to the server in the e send() meth hod can be an ny text, so thee response
f
from the serveer supplied in
n the responseText prope erty can also b
be any valid teext, whether fo ormatted or
n This means that the se
not. erver can returrn the data in HTML, XML, CSV, query sttring format, o or just plain
t
text. You can use the getRe esponseHead der() function
n of the requeest object to aascertain the ttype of data
i the responsse. The value returned is th
in he Content-Ty ponse ("text/plain",
ype of the daata in the resp
"
"text/json", "te
ext/xml", and so on). If the response is X
XML data, you can use the rresponseXML L property to
r
retrieve the wwell-formed XM ML response. The following g code shows an example:
functio
on getResponse(request) {
var
r type = request.getResp
ponseHeader(();
switch (type) {
case "text/xml" :
return request.res
sponseXML;
default :
return request.res
sponseText;
}
}
At first glance
A e, it would see em that XML is the ideal forrmat for data transfer, but remember that XML is
v
verbose, and tthat the XML LHttpRequestt object has to o parse the daata to make su ure that it is valid
v before
m
making it available in the rresponseXML L property. Th his makes usinng XML slowe er than using m more concise
p
plain text resp
ponses.
Many servers return data in
M n JSON formaat. For example, a server retturning inform
mation about musical
c
composers might pass backk the followin
ng string:
{
"su
urname": "Bach",
"ro
ole": "composer",
"firstNames": [
"Johann", "Sebastian"
]
}
5-10 Communicating with a Remote Server
Remember that JSON is a serialized view of an object. To deserialize this data, you can use the
JSON.parse() function, like this:
function getResponse(request) {
var type = request.getResponseHeader();
switch( type ) {
case "text/xml" :
return request.responseXML;
case "text/json" :
return JSON.parse(request.responseText);
default :
return request.responseText;
}
}
Remember that if the responseText property does not contain valid JSON data, then JSON.parse()
returns a null object.
Programming in HTTML5 with JavaScrippt and CSS3 5-11
1
H
Handling an Asynchronous R
Response
request
t.onreadystatechange = f
function() {
if (request.readyState ===
= 4) {
var response = JSON.pa
arse(request
t.responseText);
...
}
};
5-12 Commuunicating with a Rem
mote Server
Trransmittin
ng Data with
w a Requ
uest
Note: If th
he HTTP methhod is GET, th he body can ccontain parammeters that help to identify
the
e data that the server should return. If th
here are no pa en body can be set to null..
arameters, the
request.s
send(body);
Note: Thee actual formaat of the data expected by the server will depend on tthe server, but a
common format is JSON, as d described in m
module 3. Youu can serialize an object into JSON formaat
byy using the JSO
ON.stringify(() function.
Yo
ou should alsoo specify the fo
ormat of the data
d to ensuree that it is inte
erpreted corre
ectly by the se
erver. You
do
o this by specifying the form
mat in the Conntent-Type p property of the request hea ader. For exammple, if you
are
e sending data as a text string generated ON.stringify((), you can sett the request header as
d by using JSO
folllows:
request.s
setRequestHe
eader("Content-Type", "t
text/plain");
As another exam mple, if you arre sending daata entered byy a user on an HTML5 form
m, you should sspecify that
thiis data is enco
oded as form input, as folloows:
request.s
setRequestHe
eader("Content-Type", "a
application/
/x-www-form-urlencoded")
);
Programming in HTTML5 with JavaScrippt and CSS3 5-13
3
Lesson 2
Send
ding and
d Receiiving D
Data by Using tthe jQu
uery Lib
brary
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Serialize d
data by using jQuery helpe
er methods.
5-14 Commuunicating with a Rem
mote Server
Ussing the jQ
Query Lib
brary to Se
end Asyncchronous R
Requests
The jQuery libraary provides se ons that simplify the JavaScript needed to
everal functio o communica
ate
asyynchronously with the servver. Behind-the-scenes funcctionality is baased around the XMLHttpRRequest
ob
bject, so the co
oncepts shoulld be familiar..
Note: The
e operations performed
p uery library arre inherently aasynchronous.
by using the jQu
To
o send an HTT
TP GET requesst to a server, use the jQuerry get() function:
$.get(url
l, body, callback);
The parameters are the URL to t which the rrequest is sent, the data forr the body of the request (tthis is
op
ptional), and a callback funcction that runs when the reesponse is rece eived. The datta returned in
n response
to the request iss passed as th
he first parame
eter to the callback. The following example shows how w to send a
req
quest and hanndle the respo onse by using the jQuery get() function:
var respo
onse;
$.get('ht
ttp://contos
so.com/resources/...', f
function(dat
ta) {
respons
se = data;
});
Byy default, if an error occurs during a call tto the get() function, the ffunction fails ssilently. To handle errors,
you can chain a call to the jQQuery error() ffunction to th he end of a request. This function takes a callback
as a parameter, and runs the callback if an n error occurs while making g the request:
var respo
onse;
$.get('ht
ttp://contosso.com/resources/...', f
function(dat
ta) {
respons
se = data;
}).error(
(function {
Programming in HTML5 with JavaScript and CSS3 5-15
To send a GET request that returns JSON data, use the $.getJSON() method:
The parameters are the same as those of the get() function. However, the data is passed to the callback in
JSON format rather than as text.
To load a response directly into an element on a web page by using the jQuery library, you can use the
load() function, as follows.
In this example, the element called container is populated with the response from the web service at the
specified URL. This is useful when the response is HTML or plain text. As with the get() function, the body
parameter is optional; a null value triggers a GET operation, and a non-null value triggers a POST
operation. The callback is also optional.
5-16 Commuunicating with a Rem
mote Server
Ussing the jQ
Query ajax() Function
$.ajax({
uurl: '/lucky
ydip/enter',
ttype: 'GET',
ttimeout: 120
000,
ddataType: 't
text'
}).done(ffunction( re
esponseText ){
$('#aanswer').tex
xt( responseTText );
}).fail(ffunction() {
alertt('An error has occurred - you may not have be
een entered');
});
The url propertyy is the URL o of the web serrvice method or remote ressource. The ty ype property canc be set
to GET or POST T. The timeou ut property caauses the call tto abort after a time speciffied in millisecconds. The
daataType prope erty governs the
t response type you are expecting from the server, and can be se et to a
variety of valuess, including te
ext, xml, htm
ml, json, and sccript. The done function iss called when the call
retturns and the response datta is parsed co orrectly. The faail function iss called if the request fails ffor any
reaason.
S
Serializing
g Forms Data
D by Ussing jQuerry
$.ajax(
({
url: '/luckydip/enterW
WithName',
type: 'POST',
timeout: 12000,
dataType: 'text',
data: {
firstName: myForm.fname.valuee,
lastName: myForm.l
lname.value
}).done
e(...
).fail(
(...
);
$.ajax(
({
url: '/luckydip/enterW
WithName',
type: 'POST',
timeout: 12000,
dataType: 'text',
data: {
('#myForm').serial
lizeArray();
}
}).done
e(...
).fail(
(...
);
[
{ name: "firstName", value: "Rachel" },
{ name: "lastName", value: "Lopez" },
]
Care should be taken when using these methods because they will not include fields that are hidden or
that have a CSS display attribute set to none. Note that there is no submit button value in the array. This
is because, from a technically accurate viewpoint, the form was not submitted by using the usual form
submission mechanism.
S
Scenario
You have bee
Y en asked modiify the Scheduule page for the ContosoCo onf website. Previously,
P the
e session data
w provided as a hard-cod
was ded array of data
d and the JJavaScript codde for the pag ge displayed the data from
t array. How
this wever, session
n information is not static; it
i may be upddated at any time by the co onference
o
organizers and stored in a database. A w
web service is available thatt can retrieve the data fromm this
d
database, d you decide tto update the code for the Schedule pag
and ge to use this web service rather
r than
t hard-code
the ed data currenntly embeddeed in the application.
IIn addition, th
he conference e organizers have asked if itt is possible fo
or conference e attendees too be able to
i
indicate whichh sessions theey would like tto attend. Thiss will enable tthe conferencce organizers tot schedule
p
popular sessio
ons in larger rrooms. The Schedule page has been enh hanced to disp play star iconss next to each
s
session. An attendee can cllick a star icon
n to register th
heir interest inn that session. This informaation must be
r
recorded in a database on the server, an nd you send th his informatioon to another web service tthat updates
t correspon
the nding data in tthe database..
O
Objectives
A
After completting this lab, you
y will be able to:
1
1. Write JavvaScript code tto retrieve data from a rem
mote data source.
2
2. Write JavvaScript code tto send data to
t a remote d
data source.
3
3. Use the jQ
Query ajax method to simp
plify code that performs remote commu
unications.
E
Estimated Tim
me: 60 minutes
• User Nam
me: Student
• Password
d: Pa$$w0rd
5-20 Communicating with a Remote Server
First, you will create a function that constructs an HTTP request to get session data from a web service.
The function will send the request asynchronously, and you will define a callback function that receives
the session data when the web service replies. The session data will be a JSON string that requires parsing
into a JavaScript object. You will use the existing displaySchedule function to display the sessions on the
page.
Web services and network connections are not totally reliable. Therefore, you will need to make your code
robust enough to handle errors that can occur when receiving data. For testing purposes, a version of the
web service that generates errors is also available, and you will use this web service to verify the error
handling capabilities of your code.
Finally, you will run the application and view the Schedule page to verify that it displays the list of sessions
correctly, and also that it handles errors correctly.
2. Start the 20480A-SEA-DEV11-05 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 1
folder.
6. Also notice that the createSessionElement function has been modified to generate a star icon next
to the session title.
2. Create a function named downloadSchedule. You will add code to this function in subsequent tasks
to asynchronously get a list of sessions from a web service.
3. Within this function define a variable named request and assign it a new XMLHttpRequest object.
4. In the downloadSchedule function, use the request object to asynchronously retrieve data from the
URL /schedule/list by performing a GET operation.
5. Create a callback that handles the response from the web service and attach it to the
onreadystatechange property of the request object.
Programming in HTML5 with JavaScript and CSS3 5-21
o Ensure that the readyState property of the request object indicates the response is complete (it
should have the value 4).
o Parse the JSON string in the response into an object and assign this object to the schedule
variable.
o Call the displaySchedule function to display the sessions on the page.
7. Add a statement that calls the downloadSchedule function after initializing the event handlers for
the check boxes and list on the Schedule page.
2. Also handle the exceptional case of the remote data source returning invalid JSON data that cannot
be parsed. In this case, display a general error message using the alert function.
2. In the schedule.js file, change the requested URL to be /schedule/list?fail and then refresh the
schedule.htm page.
3. Run the application again and verify that the error message Service currently unavailable appears.
4. After testing, close Internet Explorer and change the URL back to /schedule/list.
Results: After completing this exercise, you will have modified the code for the Schedule page to displays
the list of sessions retrieved from a web service, and to handle errors that can occur when communicating
with a remote service.
5-22 Communicating with a Remote Server
First, you will create a function that creates an XMLHttpRequest object that posts data to a web service
indicating the session that a user has selected. You will encode the content of this request and set the
HTTP request headers appropriately. Next, you will handle the response and display a warning message if
the response indicates that the attendee has selected a popular session that is likely to be busy. Finally,
you will run the application and view the Schedule page to verify that the busy session message is
displayed.
The main tasks for this exercise are as follows:
1. Send the Request to Indicate the Session that an Attendee has Selected
X Task 1: Send the Request to Indicate the Session that an Attendee has Selected
1. Open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.
"/schedule/star/" + sessionId
4. In the saveStar function, use the setRequestHeader function to set the request Content-Type
header to the following:
application/x-www-form-urlencoded
5. Use the Send function to send the request, with the following body:
"starred=" + isStarred
Note: The isStarred parameter to the saveStar function is a Boolean value that indicates
whether the attendee has selected or deselected the session on the Schedule page.
o If starCount is greater than 50, display the following message by using the alert function:
Results: After completing this exercise, you will have updated the Schedule page to send attendee
selections to a web service, and to display a message when a session is popular.
5-24 Communicating with a Remote Server
2. Near the bottom of the schedule.htm file, before the reference to the schedule.js script, add a
reference to the jQuery JavaScript file jquery.min.js in the scripts folder. This action makes the
jQuery object available for use in the JavaScript code for the Schedule page.
3. In the schedule.js file in the scripts/pages folder, refactor the downloadSchedule function to use
the jQuery ajax method.
4. The ajax options object must have a type property of GET and a url property of /schedule/list.
5. Use the jQuery deferred done method to provide a callback function that handles the web service
response.
Note: The done callback is passed an argument containing the parsed JSON response
object, so you do not need to use the JSON.parse method to extract the session data.
6. Use the jQuery deferred fail method to provide a callback function that handles web service errors.
Note: The fail callback does not receive a parsed response object. You will need to use the
JSON.parse method to extract the data from the response.
2. The ajax options object must have a type property of POST and url property of "/schedule/star/" +
sessionId.
3. The data passed by using the ajax options object that specifies whether a session has been selected
should be a JavaScript object and not a string.
Programming in HTML5 with JavaScript and CSS3 5-25
4. Use the jQuery deferred done method to implement a callback function that receives the web service
response.
3. Click the star icon next to New Technologies in Enterprise and verify that an alert is displayed.
4. Click the star icon next to Diving in at the deep end with Canvas and verify that no alert is
displayed.
Results: After completing this exercise, you will have refactored the JavaScript code that sends and
receives data to use the jQuery ajax method.
5-26 Commuunicating with a Rem
mote Server
Modu
ule Reviiew and
d Takea
aways
M
Module Revie
ew
In this module, yyou have learrned how to u use the XMLH HttpRequest object
o to send
d a request to
o a remote
serrver and hand
dle any respon nse that is retu
urned. You haave seen how to perform thhese operations
syn
nchronously aand asynchron nously, and yo ou have also learned how tto catch and handle
h any errror that
miight occur when a web app plication sends a request too a remote serrver.
ou have seen h
Yo how to use the jQuery libraary to simplifyy many of the operations asssociated with
h sending
and receiving daata, and in pa
articular you h
have learned h how to use the jQuery ajaxx() function to
o perform
the
ese tasks in a concise mannner.
Q
Question
In
n the onready ystatechange
ed event hand
dler for the XMLHttpRequest object, which
p
property shouuld you examine to ensuree that data haas been return
ned, and whaat value
should this prroperty contain?
S
Select the corrrect answer.
The re
eadyState prop
perty should be
b set to 0.
The re
esponseText p
property shoulld be set to a non-null valu
ue.
The re
eadyState prop
perty should be
b set to 4.
The HT
TTPResponse property sho
ould be set to 0.
Programming in HTML5 with JavaScript and CSS3 5-27
Verify the correctness of the statement by placing a mark in the column to the right.
Statement Answer
If you use the jQuery get() function to retrieve data and you do not specify
an error handling function, any failures while retrieving the data will cause
your JavaScript code to stop with an unhandled exception. True or False?
6-1
Module 6
Styling HTML5 by Using CSS3
Contents:
Module Overview 6-2
Modu
ule Ove
erview
Wh hereas CSS1 aand CSS2.1 we ere single doccuments, the W World Wide W Web Consortiuum has chosen to write
CSSS3 as a set off modules, eacch focusing onn a single aspect of presenttation, such as color, text, b
box model,
and animations.. This allows the specificatioons to develop incrementally, along with h their implemmentations.
Each specificatioon defines prooperties and vvalues that alrready exist in CSS1 and CSSS2, and also new
prooperties and vvalues.
Ob
bjectives
e, you will be able to:
Aftter completing this module
• Use CSS3 se
electors, pseudo-classes, an
nd pseudo-ele
ements to refine the styling
g of elements.
• Enhance pa
ages by using CSS3 graphiccal effects.
Programming in HTML5 with JavaScrript and CSS3 6-3
3
Lesson 1
Stylin
ng Textt by Using CSS
S3
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain th
he different raanges of value
es you can apply to CSS fon
nt and text properties.
Fo
onts and Measurem
M ments
@font-face
We eb designers have, until reccently, been restricted when deciding ho ow to render ttext to the sett of fonts
insstalled by defa
ault on differe
ent operating systems. Thiss limitation haas often resultted in using a
combination of web-safe fon nts for generall text and the replacement of particular headings with h a graphic
of that heading's text in a diffferent font.
The @font-face e rule enabless you to specify a font file tto download, give it a name
e, and then usse it in your
CSSS rules just likke any other w
web-safe font such as Time es, Arial, and H
Helvetica.
The following exxample showss how to use thet @font-faace rule to dow
wnload the TrrueType® verrsion of the
Ro
oboto Regularr font, and use
e it to style so
ome paragraph
hs.
The @font-face
e rule implem
ments a combination of properties that define how a browser
b should use a
fon
nt:
• font-weight identifies the boldness of the font; bold, normal, or a value between 100 and 900.
• unicode identifies the range of Unicode characters the font supports.
Only the font-family and src properties are required, but if you have access to the font files for
condensed, bold, or italic variants of the same font, you should prefer to use these rather than let the
browser style the text itself. The purpose of the optional properties is to give the browser hints that these
font variants are available, as shown in the following examples:
@font-face {
font-family: 'RobotoRegular';
src: url('Roboto-Regular-webfont.ttf') format('truetype');
}
@font-face {
font-family: 'RobotoRegular';
src: url('Roboto-Regular-B-webfont.ttf') format('truetype');
font-weight: bold;
}
@font-face {
font-family: 'RobotoRegular';
src: url('Roboto-Regular-I-webfont.ttf') format('truetype');
font-style: italic;
}
You should also note that while most web browsers support the @font-face rule, they do not all support
the same font formats. You actually require four font file formats for complete support (embedded-
opentype, woff, truetype, and svg). The following example shows how to download the font files that
support these formats:
@font-face {
font-family: 'RobotoRegular';
src: url('Roboto-Regular-webfont.eot');
src: url('Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'),
url('Roboto-Regular-webfont.woff') format('woff'),
url('Roboto-Regular-webfont.ttf') format('truetype'),
url('Roboto-Regular-webfont.svg#RobotoRegular') format('svg');
}
Note: You should not distribute font files around the web unless you have a license to do
so. However, there are many open source fonts available, and several font webshops will sell you
a font and the required license.
Measurements
When you set the font-size property, the most common units used for that property are points for print
style sheets and pixels for screen style sheets. However, CSS3 defines several additional units of
measurement that can be applied to boxes, columns, and images, and for positioning these items.
• Centimeters.
• Millimeters (mm): 10 millimeters = 1 centimeter.
• ex: 1ex = the height of the font's lowercase x-height, or 0.5 em if not calculable.
• rem: 1rem = the size of the font defined on the html element (16px default)
The other three are 'viewport-relative'. That is, they are relative to the size of the browser window object:
You can also use the calc() function to calculate a measurement at runtime. For example:
img {
max-height: calc(100vh - 5px);
max-width: calc(100vw - 5px);
}
In this case, the height and width of an image is set to a maximum of the browser window height and
width minus 5px. This ensures you can always see the full image in your browser.
Programming in HTML5 with JavaScrript and CSS3 6-7
7
I
Implemen
nting Textt Effects
text-in
ndent: 3rem;
hyphens
s: manual;
-ms-hyp
phens : manual; // IE10
0
• The wordd-wrap prope erty, which inddicates whether the browse er may break lines within words
w when
line-wrap
pping. Possible
e values are n efault is no), and break-worrd (the browser may break
normal (the de
words at an arbitrary p
point). It has b
been renamed d overflow-wraap in CSS3, buut at this time
e browsers
only reco
ognize the old name.
word-wr
rap : normal;
• The wordd-spacing pro operty, which enables you tto set the spaacing between
n words in a b
block of text.
You can u
use both relattive and absollute measurem
ments.
word-sp
pacing : 5px;
word-sp
pacing : 2rem;
o blur (optional): How wide the blur of the shadow is. The default is 0.
Reference Links: You can find the current draft of the CSS3 Text Module at
http://go.microsoft.com/fwlink/?LinkID=267726.
Programming in HTML5 with JavaScrript and CSS3 6-9
9
Lesson 2
Stylin
ng Blocck Elem
ments
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to
Ou
utlines
CSSS defines an ooutline box inn addition to tthe four conce
entric boxes (ccontent, padd
ding, border, and
a
maargin) that maake up the bo ox model. How wever, an outline does not add to the total width or hheight of
thee box. Instead
d, it is drawn above
a the margin box, and defined relattive to the boxx's border. Ou
utlines can
theerefore overlaap on a page.
The following exxample showss how to draw d an outline aaround a box. The outline iss drawn
w a border and
5p
px away from tthe border.
Ad
dding an Outtline
d
div {
border: 2px solid red;
outline
e: 2px solid
d green;
outline
e-offset: 5p
px;
}
/
/* The above code can al
lso be writt
ten in full a
as */
d
div {
border-widt
th: 2px;
border-styl
le: solid;
border-colo
or: red;
outline-wid
dth: 2px;
outline-sty
yle: solid;
outline-col
lor: green;
outline-off
fset: 5px;
}
Ou
utlines are deffined by four properties:
• outline-offset sets the distance between the outline and the border.
You can use outline as a shorthand property for the outline-width, outline-style, and outline-color
properties, in that order. The outline-offset property is new in CSS3 and must be declared separately, as
shown in the previous example.
Presentation
There are several new design-related box properties in CSS3.
• The border-radius property enables you to set rounded corners on a box's border by defining the
radius of the circle or radii of an ellipse around which the corner will bend.
Note that border-radius is a shorthand property. You can set the radius of each of the four border corners
individually by using the border-top-left-radius, border-top-right-radius, border-bottom-right-radius, and
border-bottom-left-radius properties.
• The overflow-x and overflow-y properties enable you to set what happens when the content of an
element is too wide or too high for the box that contains it. Possible values are:
o visible: The content is not clipped and is rendered outside of the box. This is the default.
o scroll: Only the content within the box is shown, but a scrollbar is displayed so the rest of the
content can be viewed.
These are the same values as for the overflow property, which applies to both x- and y-axes.
overflow-x: hidden;
overflow-y: scroll;
• The resize property enables you to mark a text block as resizable, assuming that the overflow
property has already been set to hidden or scroll. Possible values are none (the default), both,
horizontal, and vertical, denoting in which axes the element should be resizable.
overflow: hidden;
resize: horizontal;
min-width: 60px;
max-width: 400px;
Note: It's a good idea to set a minimum and maximum height for a block marked as
resizable so that the user doesn't break the page layout completely by changing the size of the
browser window.
The following example shows how to style section elements to use a three-column layout with a 5rem
gap between columns and a dotted line between each column.
column-count : 3;
column-gap : 5rem;
column-rule : 1px solid black;
}
There are four main properties for creating multiple column layouts:
Support for multiple-column layouts is limited at present, although it is available in Internet Explorer 10.
Reference Links: You can find the latest draft of the CSS3 Multi-Column Layout Module at
http://go.microsoft.com/fwlink/?LinkID=267727.
Programming in HTTML5 with JavaScrippt and CSS3 6-13
3
B
Block Layo
out Mode
els
display
y:block;
display
y:inline;
display
y:inline-block;
• table: Tab
ble layout enaables you to id
dentify blockss on the page
e as tables, row
ws, columns, aand cells.
Blocks are
e aligned by ttheir edges rather than their content, and sized to fit tthe computedd table.
display
y:table;
display
y: flexbox; // for a block-leve
el flexbox container
display
y: -ms-flexbox;
display
y: inline-flexbox; // for an inline flexbox container
display
y: -ms-inline-flexbox;
6-14 Styling HTML5 by Using CSS3
Note: Note that the display values for enabling flexbox layout were correct when written;
the values may change before the CSS3 Flexbox Module is finalized.
All of these layout models (possibly with the exception of flexbox, depending on the final implementation)
assume that blocks are arranged according to the normal flow of elements. For example, with the code
below, the normal flow of elements would position div1 on the page first then div2 next to it, div3 next
to div2, and div4 next to div3, and all four div elements would be placed inside the article element:
<article>
<div id="1">One</div>
<div id="2">Two</div>
<div id="3">Three</div>
<div id="4">Four</div>
</article>
These blocks all have the default CSS position value of static. You can take any of these blocks out of the
normal flow by changing their position property to relative, absolute, or fixed.
If you set position to relative, you can use the top, right, bottom, and left properties to position the
block relative to the position it would have been in. All other blocks stay in the same position they would
have been in, as if the block was statically rather than relatively positioned.
position: relative;
top: -10px; // Top edge of block moved up 10 pixels from normal
left: 10px; // Left edge of block moved right 10 pixels from normal
If you set position to absolute, the block is taken completely out of the normal flow and positioned
relative to the edges of its containing block. In the following styling, if div2 were absolutely positioned,
div3 would be positioned next to div1 in the normal flow.
position: absolute;
top: 25px; // Top edge of block 25 pixels down from top edge of container
right: 10px; // Right edge of block 10 pixels left from right edge of container
If you set position to fixed, the block is out of the normal flow and positioned relative to the edge of the
browser window (technically, the viewport).
position: fixed;
bottom: 0; // Bottom edge of block in line with bottom edge of browser window
right: o; // Right edge of block in line with right edge of browser window
Programming in HTTML5 with JavaScrippt and CSS3 6-15
5
D
Demonstr
ration: Sw
witching B
Between C
CSS Layoutt Models
D
Demonstra
ation Steps
S
Switch betwee
en layout mod
des in a web page
p
1
1. On the W
Windows 8 Sta
art screen, clicck the Visual S
Studio 2012 tile.
2
2. In Visual Studio, on the
e File menu, p
point to Open
n, and then click File.
3
3. In the Op g, browse to tthe E:\Democcode folder, cclick positioning.html, and
pen File dialog d then click
Open.
4
4. Review th
he code with tthe students. T ents. The file
This file contaains an HTML article with ffour div eleme
also contaains styles forr the article and div elements.
<!DOCTYPPE html>
<html xmmlns="http:/
//www.w3.org/1999/xhtml"
">
<head>
<titlee>Positionin
ng Demo</title>
<stylee type="text
t/css">
bodyy {
te
ext-align: center;
c
}
artiicle {
pa
adding: 10px
x;
bo
order: 2px solid
s red;
}
div {
ma
argin: 10px;
;
pa
adding: 5px;
;
bo
order: 2px solid
s black;
wi
idth: 150px;
;
he
eight : 150p
px;
}
div:nth-child(oodd) {
fo
ont-size: 4r
rem;
}
</stylle>
</head>
6-16 Styling HTML5 by Using CSS3
<body>
<article>
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<div id="four">Four</div>
</article>
</body>
</html>
6. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
7. Observe the four div elements laid out underneath each other, in order, within the article element.
The article element has a red border to highlight its boundaries. This is block layout mode.
Programming in HTTML5 with JavaScrippt and CSS3 6-17
7
FIGUR
RE 6.1: THE DIV ELEMENTS
S IN BLOCK LAYOUT
L MODE
8
8. Press F12
2.
9
9. In the F12
2 Developer Tools
T pane, prress CTRL+P to t unpin the w
window. Posittion the F12 D
Developer
Tools winndow so that yyou can see th
he Internet Exxplorer window
w at the samee time.
1 Type disp
12. play: inline, aand then presss ENTER.
1 In Interne
13. et Explorer, no
otice that the four div elem
ments are now w laid out side-by-side align
ned by text
baseline w
with height annd width prop perties ignore
ed. This is inlin
ne layout modde.
16
6. Notice the layout is the ssame but the height and w
width propertties are now p
preserved. Thiss is inline-
block modee.
The web pa
age now lookss like this:
19. Switch to In
nternet Explorrer to view the
e new layout. The div elem
ments are displlayed in a verttical
column.
20
0. In the F12 D
Developer Too ols window, o
on the CSS tab
b, click the dissplay: -ms-fle
exbox rule, ch
hange it to
display:tabble-cell, and tthen press EN
NTER.
Programming in HTML5 with JavaScript and CSS3 6-19
21. Switch to Internet Explorer to view the new layout. The div elements are displayed in a horizontal
table.
1. In the F12 Developer Tools window, on the CSS tab, clear the three checkboxes next to the display
attributes for body, article, and div.
2. Right-click the div entry, and then click Add rule after.
• In Internet Explorer, notice how the three box is positioned relative to its normal position.
9. In the F12 Developer Tools window, on the CSS tab, click the position:relative rule, change it to
position:absolute, and then press ENTER.
• In Internet Explorer, notice how the three box is now positioned relative to its containing article
block.
10. In the F12 Developer Tools window, on the CSS tab, on the CSS tab, click the position:absolute rule,
change it to position:fixed, and then press ENTER.
• In Internet Explorer, notice how the three box is positioned relative to the browser window. Make the
window small enough to require scrolling and see how the three box remains stationary when you
scroll.
Lesson 3
Pseud
do-Classses and
d Pseud
do-Elem
ments
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
T
Text Pseudo-Eleme
ents
Text-based psseudo-elemen
T nts match elemments that aree not easily id
dentifiable in tthe documentt tree for a
p
page. The following list desscribes some o
of the more ccommonly use ed pseudo-ele ements. Notice that in a
C rule you u
CSS use a double colon to conccatenate them m to a text itemm.
• first-lette
er selects the first characte ntent of an element.
er of the first liine of text con
p::firs
st-letter{ }
• first-line
e selects the first line of textt content of an element.
p::firs
st-line{ }
• before se
elects the spacce immediate
ely before an e
element.
p::befo
ore{ }
• after sele
ects the space
e immediately after an elem
ment.
p::afte
er{ }
• selection
n selects the p
part of the pag
ge that has be
een highlighte
ed by the user.
::selec
ction{ }
blockquote::before, blockquote::after,
q::before, q::after {
content:'';
content:none;
}
Note that before and after are only applicable to elements that contain text content.
Note: In CSS1 and CSS2, pseudo-elements start with a colon (:). In CSS3, pseudo-elements
start with a double colon (::) to differentiate them from pseudo-classes. However most browsers
still use single colons.
Programming in HTTML5 with JavaScrippt and CSS3 6-23
3
L
Link and FForm Pseu
udo-Classes
Pseudo-classe
P es are like pse
eudo-elements in that they match eleme ents that are n
not part of the
e document
t
tree. Howeverr, the pseudo--classes are no
ot text elemen
nts; rather, the
ey match against the resultt of user
i
interaction with the page. In ou concatenaate them to elements by using a single co
I CSS rules yo olon.
T
There are five
e pseudo-classses for hyperliinks:
• a:link sele
ects all unvisitted links.
• a:hover sselects all linkss with the currsor hovering over them.
T
There are thre
ee pseudo-claasses that you frequently usse for forms e
elements:
• input:ena
abled selects all enabled in
nput controls.
• input:che
ecked selects all user interfface elements that are checcked.
6-24 Styling HTML5 by Using CSS3
Note: Forms elements also provide the :valid and :invalid pseudo-classes that you can use
to select items that have been validated successfully or unsuccessfully. This subject was covered in
module 4.
Programming in HTTML5 with JavaScrippt and CSS3 6-25
5
D
DOM-Rela
ated Pseu
udo-Classe
es
IIn addition to
o link and formm-related pseu udo-classes, other
o pseudo--classes are avvailable that e
enable you to
i
identify speciffic elements in
n a selected set based on their position in the DOM. FFor example:
• :nth-last-child(n) sele
ects a list item
m if it is the nth
h child of its parent,
p counting backwardss from its last
child.
Another set enables you to
A o select eleme
ents based on their position
n in the DOM and their typee. For
e
example:
• :first-of-type selects a list item if it is the first listt item child off its parent.
• :last-of-ttype selects a list item if it iis the last list item child of its parent.
• :only-of type selects a list item if it is the only lisst item child o
of its parent.
• :nth-of-ttype(n) selectts a list item iff it is the nth list item child of its parent.
• E:not(s) selects any element which does not match the selector string s.
Note: Remember: Pseudo-classes qualify the element they are attached to rather than
specifying other elements. For example, li:first-child selects a list item that's the first child of its
parent, and not the first child of the list item.
Programming in HTTML5 with JavaScrippt and CSS3 6-27
7
Lesson 4
Enha
ancing G
Graphiccal Effe
ects by Using C
CSS3
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
Sp
pecifying Color Values
Yo
ou use the CSSS color propeerty to modify the color of ttext content. CSS3
C extends this functiona ality by
enabling to app
ply color backggrounds, bord ders, outlines, column ruless, and more. Itt is importantt to be
aw
ware of the maany different ways
w of speciffying color values and how
w CSS3 implem ments transparrency.
The CSS3 Color module defin
nes several value ranges forr the color prroperty:
color: ye
ellow;
color: #f
ff0; /* #
#rgb */
color: #f
ffff00; /* #
#rrggbb */
color: rg
gb(255, 255, 0);
color: rg
gb(100%, 100
0%, 0%);
color: rg
gba(255, 255
5, 0, 0.2); /* mostl
ly transpare
ent yellow */
/
color: rg
gba(100%, 10
00%, 0%, 0.8); /* mostl
ly opaque ye
ellow */
color: tr
ransparent;
• A hue-saturration-lightneess (HSL) model value speciified as a triplet of numbers. The first is aan integer
value betwe een 0 and 3600 indicating th
he angle of th
he color circle (0 = red, 120
0 = green, 240 0 = blue).
The second is a percentaage value for ssaturation where 0% is a sh hade of grey aand 100% is fu ull color.
The third is also a percen
ntage value fo
or lightness, w
where 0% is blaack, 100% is wwhite and 50% % is normal.
color: hs
sl(60, 100%, 50%);
Programming in HTML5 with JavaScript and CSS3 6-29
• The keyword inherit. This indicates that the element should inherit the same color value as its parent
element.
• The keyword currentColor. This indicates the same value should be used as that of the element's
color property. Writing color:currentColor is the same as writing color:inherit.
Additional Reading: For a complete list of valid color names and a more in-depth
description of the HSL model, read the current CSS3 Color Module Specification at
http://go.microsoft.com/fwlink/?LinkID=267728.
6-30 Styling HTML5 by Using CSSS3
Defining Baackground
ds and Efffects
Multi-Image Backgroun
nds
CSSS3-compliantt browsers now w support thee use of multiple background images within an eleme
ent.
Coonsequently, every
e backgro ound image-re elated propertty in CSS3 now
w takes a com
mma-separate
ed list of
values rather than just one, as shown in the following exxample:
article {
bac
ckground-ima
age: url('bluearrow.png'
'), url('gre
eenarrow.png');
bac
ckground-rep
peat: repeat-x, repeat-y
y;
}
In this rule, blueearrow.png wiill be repeated d left to right along the top
p edge of the article elemeent and
greeenarrow.png g will be repeaated top to boottom along tthe left edge ofo the article element. Thee image
deeclared first in the list appeaars on top of the others, soo bluearrow.pnng appears abbove greenarrrow.png in
thee top left cornner of the artiicle element. You can use tthe backgrou und-position to move each h image
aroound the othe er to achieve a specific effe
ect.
article {
bac
ckground: ur
rl('bluearrow
w.png') repe
eat-x, url('greenarrow.png') repeat
t-y;
}
Grradients
CSSS3 enables yoou to define a color gradien
nt as a value ffor any prope
erty that would
d take an image. Most
ob
bviously, this would
w apply to
o background ds. You can se
et two types of gradient:
The direction parameter is optional and is set in degrees; the default is 180deg. The start-color and end-
color parameters can be set to any of the color values listed in the previous topic. You can also set any
number of intermediate colors between the start and end, which the browser will space out evenly over
the gradient line.
• A radial gradient, which is a gradual change in color from a central point in the start-color outwards
in either a circle or an elliptical shape to the end color at the edge of the shape. Any number of
intermediate colors can be set in the list.
The position parameter is optional. Its default value is center. The shape parameter is also optional. Its
default value is circle; the only other option is ellipse.
Note that most modern browsers, with the exception of Internet Explorer 9 and earlier versions, support
gradients, but only with vendor-prefixes attached.
6-32 Styling HTML5 by Using CSSS3
Im
mplementing Transfformation
ns and Gra
aphics
Trransforming
g Elementss by Using C
CSS3
The CSS3 transfform propertyy can be applieed to any block-level element. You set itts value to either one of
the
e following traansformation functions, or to none to in ansform should be applied:
ndicate no tra
• translate3d
d(x,y,z) : Movves the whole element by thet distance x along the x-a axis, y along tthe y-axis,
and z along
g the z-axis. The values for x, y, and z can be any valid
d unit of measurement.
transform
m: translate
e3d(10px, 50px, 10px);
• translate(x
x,y) : 2d varian
nt of translate3d().
• translateX((x), translate
e(y), translate
eZ(z) : Single aaxis variants o
of translate3d
d().
• scale3d(x,yy,z) : Scales th
he element's ssize by a facto
or x along the x-axis, y alon
ng the y-axis, and z
along the z-axis. The valuues for x, y, and z must be positive num mbers (use a deecimal value less than 1
to shrink an
n element in a given dimen nsion).
transform
m: scale3d(2
2, 4, 0.5);
transform
m: rotate(30
0deg);
Note that most modern browsers, with the exception of Internet Explorer 9 and earlier versions, support
transforms, but only with vendor-prefixes attached.
transform: rotate(30deg);
-ms-transform: rotate(30deg); // IE10
#square {
width: 200px;
height: 200px;
background: blue;
}
You can draw shapes such as circles and ovals by using the border-radius property to add curves to a
square.
#circle {
width: 200px;
height: 200px;
background: blue;
border-radius: 50%;
}
#triangle-topleft {
width: 0;
height: 0;
border-top: 200px solid blue;
border-right: 200px solid transparent;
}
Adding 2D transforms such as rotations and skews enables you to create stars, parallelograms, and many
more complex shapes.
6-34 Styling HTML5 by Using CSSS3
Lab: S
Styling T
Text an
nd Block Eleme
ents by
y Using CSS3
Sccenario
The Contoso Co onference web
b application needs to be visually
v appealing. A design
ner has produced mock-
up
p designs of so
ome of the pa
ages that you have been assked to implemment for the w
website.
Yo
ou will be working on the Home
H and Abo out pages. The HTML page e structure hass already been
n created.
Yo
ou will use CSSS to style vario
ous parts of th
he pages, to make
m them match the desig gns. Much of the CSS
tha
at you create, such as the navigation
n linkks bar, will be reused by other pages.
Some aspects off the design are
a complicate ed and would have require ed images with
h previous verrsions of
CSSS. However, by
b using CSS3, you will not need to creatte any imagess.
Ob
bjectives
Aftter completing this lab, you
u will be able to:
• Create grap
phical elements by using CSSS.
• Password: Pa$$w0rd
P
Programming in HTTML5 with JavaScrippt and CSS3 6-35
5
E
Exercise 1
1: Styling tthe Navigation Bar
S
Scenario
I this exercise, you will styyle the navigattion bar for th
In he website.
Y will use C
You CSS to style the navigation bar to look sim
milar to the fo
ollowing imag
ge:
FIGUR
RE 6.4: THE NAVIGATION BAR
The HTML maarkup for the navigation ba
T ar is simply a ccollection of <
<a> elementss. The links are e arranged as
h
horizontally sttacked blockss, which maxim
mizes the clickk area. You wiill style the acctive page linkk with a linearr
g
gradient and red ribbon efffect.
FFinally, you w
will run the app
plication, view
w the Home page, and veriffy that the navvigation bar looks similar
t above imaage.
the
Note: T
The layout of tthe Home pag ge has also ch
hanged slightly. The imagess of the speakkers
a the sponssor's logos have been laid out
and o in a grid bby using the Flexible
F Model display style.
Box M
X Task 1: Review
R the HTML Structure
1
1. Start the MSL-TMG1 virtual
v machin
ne if it is not aalready runnin
ng.
2
2. A-DEV11-06 vvirtual machine if it is not already running, and log on
Start the 20480A-SEA n as Student
with the p
password Pa$
$$w0rd.
3
3. Start Visu
ual Studio and ontosoConf.sln solution fro
d open the Co om the E:\Lab
bfiles\Starterr\Exercise 1
folder.
4
4. In the Co
ontosoConf, project
p open tthe index.htm
m file.
Notice th
hat the <head
d> has a link tto the /styles//nav.css style
e sheet.
5
5. Find the <
<nav> eleme
ent, at the starrt of the <bod
dy>.
6
6. Run the aapplication, view the Home
e page, and no
otice that the navigation lin
nks are curren
ntly unstyled.
6-36 Styling HTML5 by Using CSSS3
X Task 2: Sty
yle the Nav
vigation Barr and Links
1. Open the n
nav.css style sheet in the styyles folder.
• Using the n
nav.page-nav v selector, set the backgrou
und color to #
#1d1d1d, set tthe line height to 6rem,
and set the font size to 1
1.7rem.
6
6. Add a CSS rule for the active navigaation link. Makke the text color white and the backgrou
und a linear
gradient ffrom #c956566 to #8d0606..
7
7. Override the text colorr when the mo
ouse hovers o
over the active
e link. Make th
he text white.
X Task 3: Create
C Grap
phics by Usiing Pseudo Elements
1
1. Add two CSS rules, usin ng the :beforre and :after pseudo
p eleme
ents that gene
erate triangle shapes
below the
e active link, tto simulate a ribbon
r effect.
The follow
wing example
e CSS generates a black tria
angle:
.example
e:after {
cont
tent: "";
bord
der-top: 100
0px solid #000;
bord
der-left: 10
00px solid transparent;
disp
play: block;
;
posi
ition: absol
lute;
}
RE 6.8: THE FU
FIGUR ULLY STYLED
D NAVIGATIO
ON BAR
X Task 4: Test
T the Naavigation Ba
ar
1
1. Run the aapplication, view the home e.htm page an
nd verify that the navigatio
on bar looks siimilar to the
following
g image shown n in the previo
ous task.
2
2. Use the n at the style of the active item in the
navigation barr to move between pages, aand verify tha
navigatio
on bar is displaayed by using
g the ribbon effect.
3
3. Close Inte
ernet Explorerr.
Exxercise 2: Styling th
he Register Link
Sccenario
In this exercise, you will style the large Reg
gister link thaat appears in the
t header off the Home paage.
Cuurrently this lin
nk is unstyled, but you have
e been asked to make it sta and out so that users will n
notice it.
A designer
d has provided
p the following imaage showing h
how the Regisster link shou
uld appear:
1. Review the HT
TML and CSS
2. Position the R
Register Link aand Set the Te
ext Styling
X Task 1: Re
eview the H
HTML and CSS
1. Open the C
Contoso.conff solution in th
he E:\Labfiless\Starter\Exe
ercise 2 folderr.
3. Notice that the <head> element conttains a link to the header.ccss style sheett in the styless folder.
4. Find the <hheader> elem ment and revie ew the contennts. Notice thaat the header contains the HTML
markup for the Registerr link. Also nottice that the class
c of the he
eader is page--header and tthat the
class of the Register link is register.
X Task 2: Po
osition the R
Register Lin
nk and Set the Text Sty
yling
1. Open the h
header.css file
e in the styless folder.
2. Find the currently emptyy CSS rule for the register cclass of the paage header. Add
A the follow
wing styling
to this rule:
• Position the
e Register link near the top
p-right of its ccontainer.
Programming in HTTML5 with JavaScrippt and CSS3 6-39
9
3
3. Set the fo
ont-size, textt-alignment, text-decorattion, and textt-transforma
ation properties for the
Register link:
• Make the
e text appear in
i upper case with a font siize of 2.7rem.
• Set the te
ext color to white.
• Add a 1p
px black text shadow.
• Set the te
ext alignment to center.
• Do not ap
pply any additional text decoration.
If you run
n the applicatiion at this point, the Registter link will loo
ok like this in the page hea
ader:
FIGUR
RE 6.10: THE R
REGISTER LIN
NK
X Task 3: Style
S the Re
egister Link Backgroun
nd, Shape, and Rotation
n Propertiess
1
1. The Regisster link is currrently quite d
difficult to see. Add a linearr gradient bacckground to th
he Register
link. Use tthe colors #a880000 and #7 740404.
2
2. Set the bo
order-radiuss property to m
make the Reg
gister link circcular.
3
3. Rotate the Register lin
nk 6 degrees cclockwise.
4
4. Implemen nt the headerr.page-headeer .register:hover CSS rule
e, to change th
he backgroun
nd linear
gradient colors to #bc0
0101 and #8cc0909 when th he mouse hovvers over the link.
l
5
5. Implemennt the headerr.page-heade er .register:before CSS rule to create a circular, dotte
ed border
around th
he Register link. Specify th
he border coloor #740404.
6
6. Make thee border slighttly wider and taller than the Register lin
nk, and adjust the position of the borderr
to center it on the link (adjust the to
op and right properties byy -0.7rem.)
X Task 4: Test
T the Reg
gister Link
1
1. Run the aapplication an
nd view the in
ndex.htm pag
ge. :
3
3. Close Inte
ernet Explorerr.
6-40 Styling HTML5 by Using CSS3
Results: After completing this exercise, you will have styled the Register link in the header of the Home
page.
Programming in HTTML5 with JavaScrippt and CSS3 6-41
1
E
Exercise 3
3: Styling tthe Aboutt Page
S
Scenario
IIn this exercise, you will styyle the About page. This paage only contains text, but to make it loo
ok attractive
y will use so
you ome advanced typographyy styling.
FFirst you will fflow the text oover three collumns and add a "drop cap p” style to the first letter. Th
hen you will
s
style a testimo onial quote. FFinally, you will run the app
plication, view the About paage, and verifyy that it lookss
l
like the follow
wing image:
T About paage should loo
The ok like this wh
hen it is comp
pleted:
FIGUR
RE 6.12: THE A
ABOUT PAGE
E
T main taskks for this exerrcise are as fo
The ollows:
3 Add a Drop
3. p Cap at the SStart of the Text
4 Indent Para
4. agraphs
6 Test the Ab
6. bout Page
X Task 1: Review
R the HTML and CSS
1
1. Open the
e Contoso.con
nf solution in the E:\Labfilles\Starter\Ex
xercise 3 fold
der.
2
2. In the Co
ontosoConf project,
p open tthe about.htm
m file.
3
3. In the <h
head> elemen
nt notice there
e is a link to the about.css style sheet in
n the /styles/p
pages folder.
4
4. Review thhe <article cla
ass="contain
ner"> HTML markup.
m This article contain
ns the text thaat is displayed
d
in the bod
dy of the Aboout page. You
u will add styliing to this ma
arkup.
6-42 Styling HTML5 by Using CSSS3
X Task 2: De
efine Text C
Columns
1. Open the about.css file in the styles//pages folder.
• Flow the co
ontent over th
hree columns.
• Add a gap o
of 5rem betw
ween the colum
mns.
X Task 3: Ad
dd a Drop C
Cap at the S
Start of the T
Text
1. In about.csss, add a CSS rule that makkes the first lettter of the firsst paragraph laarger:
2. Note that the first paragraph does not require inde entation becauuse it already has a drop caap effect;
add a CSS rrule for the firrst paragraph, which resets the indentation and margiin.
X Task 5: Sty
yle the Blocck Quote
1. In about.csss, add CSS ru
ules that style blockquote elements
e to lo
ook like the fo
ollowing imag
ge:
• Use a com
mbination of position
p relative and abso
olute to posittion the :befo
ore element re
elative to the
block quo
ote.
X Task 6: Test
T the Ab
bout Page
1
1. Run the aapplication an
nd view the Ab
bout page.
The Abou
ut page should
d look like thiis:
FIGUR
RE 6.15: THE A
ABOUT PAGE
E
2
2. Close Inte
ernet Explorerr.
R
Results: Afterr completing this
t exercise, you
y will have styled the texxt on the Abo
out page.
6-44 Styling HTML5 by Using CSSS3
Modu
ule Reviiew and
d Takea
aways
M
Module Revie
ew
In this module, yyou have learrned how to uuse the new feeatures of CSSS3 to provide advanced formatting for
texxt, color, and backgrounds.. You have alsso seen how CCSS pseudo-ellements and p pseudo-classe
es offer a
very fine level oof control whe
en it comes to selecting elements to style
e.
ou have also le
Yo earned how CSS3
C offers alte
ernative wayss to position e
elements on a page that are
e in
addition to the traditional bo
ox model, andd how to use CCSS propertiess in combinattion to genera
ate simple
gra
aphics.
Q
Question
W
Which CSS rulle can you use
e to downloa
ad a font requ
uired by a we
eb page?
S
Select the corrrect answer.
@fontt-family
@fontt-style
@fontt-face
@fontt
Question: What
W are the main differen
nces between the CSS box m
model, flex-bo
ox, and multi--
column layo
out?
Question: How
H do you sselect the firstt item in a list so that you ccan apply styling to it?
7-1
Module 7
Creating Objects and Methods by Using JavaScript
Contents:
Module Overview 7-2
Modu
ule Ove
erview
Co
ode reuse and ease of mainntenance are kkey objectivess of writing we
ell-structured applications. If you can
me
eet these obje
ectives, you w
will reduce the costs associated with writing and mainttaining your ccode.
Ob
bjectives
Aftter completing this module
e, you will be able to:
Lesson 1
Writiing We
ell-Strucctured JavaScrript Cod
de
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain th
he scoping rules for local va
ariables, and describe
d how hoisting workks.
• Use immeediately invokked functions, strict mode, and namespaaces to minimiize global nam
me clashes in
a web application.
• Use comm
mon global ob
bjects and fun
nctions availab
ble in the stan
ndard JavaScrript language.
7-4 Creating Objects and Methodds by Using JavaScrript
JavvaScript has m
many syntacticc similarities to other popular contempo orary program mming languag ges such as
C##, C++, and Jaava. However, there are sevveral subtle diffferences thatt often surprisse experienced
d
evelopers, because the syntax looks similar but has a different
de d mean ning.
On
ne area of connfusion for som me developerrs concerns th
he concept of scoping and hoisting. The term scope
de
escribes the vissibility of a va
ariable. When you declare a variable in JaavaScript, it has one of two
o scopes:
• A variable h
has global sco
ope if it define
ed outside of a function.
• A variable h
has function scope if it is de
efined inside a function.
• The demon nstrateScopin ngAndHoisting() function declares a local variable named num in nside an if
statement b block, and asssigns it the vallue 42. This vaariable is hoistted automaticcally to function scope,
as if it was d
declared at th
he start of the demonstrate eScopingAnd dHoisting() function.
• After the if statement, th
he local num vvariable is still in scope. The
erefore the allert() function
n displays
the local nu
um variable (442), not the gllobal num variable (7).
<script>
var nnum = 7;
functtion demonsttrateScopingA
AndHoisting(
() {
iif (true) {
var num = 42;
}
aalert("The vvalue of num is " + num)
);
}
</script>>
Programming in HTML5 with JavaScript and CSS3 7-5
7-6 Creating Objects and Methodds by Using JavaScrript
M
Managing t Globaal Namesp
the pace
• es
Namespace
• Strict mode
e
Im
mmediately
y Invoked Fu
unctions
An
n immediatelyy invoked funcction is a funcction that is de
efined and run immediatelyy. You define an
immediately invvoked function by wrapping g it in an anonymous functtion call that is immediatelyy executed.
The following exxample showss the syntax foor an immediaately invoked function:
(functio
on() {
// St
tatements in
nside the function…
}) ();
Ann immediatelyy invoked funcction is run ass soon as it has been define
ed. Any variab
bles and otherr functions
cre
eated inside th
he function body are scope ed to the imm mediately invo
oked function,, and they disaappear as
sooon as the imm
mediately invo
oked function has finished. In this way, yyou can guarantee that thesse variables
and functions will
w not pollute e the global namespace.
Maany JavaScriptt programmers use this tecchnique to enssure that the JJavaScript cod
de specific to a web
page is isolated from the JavaaScript code ffor other web pages.
Programming in HTML5 with JavaScript and CSS3 7-7
Namespaces
JavaScript namespaces provide another way to avoid global name clashes. In JavaScript, a namespace is a
global variable with variables and functions attached to it.
The following example shows how to define a namespace named MyNamespace, containing two
functions and two variables:
var MyNamespace = {
myFunction1: function(someParameters) {
// Implementation code…
},
myFunction2: function(someParameters) {
// Implementation code…
},
message: "Hello World",
count = 42
}
Outside of the namespace declaration, you can access its functions and variables by using a qualified
name that specifies the namespace. The following example shows how to access namespace members:
MyNamespace.myFunction1(someParameterValues);
MyNamespace.message = "Goodbye all";
Namespaces do not provide any privacy or encapsulation; the members defined inside a namespace are
completely visible to external code, by using properly qualified names such as those shown in the
previous example.
Strict Mode
The rules for declaring variables in JavaScript are fairly relaxed. If you omit the var keyword in a variable
declaration, the variable is implicitly given global scope. This means you can accidentally declare a new
global variable without realizing it, as illustrated in the following example:
function someFunction() {
var errorCode = 100; // Declares a local variable named errorCode.
count = 0; // Implicitly declares a global variable named
count;
...
}
To avoid accidentally declaring global variables by omitting the var keyword, you can use strict mode as
follows:
function someFunction() {
"use strict";
// Other statements.
}
When you use strict mode, you will get an error if you try to declare a variable without using var;
JavaScript will not automatically promote the variable to global scope.
7-8 Creating Objects and Methodds by Using JavaScrript
Singleton O
Objects an
nd Global Functionss in JavaSccript
Onne of the best known design patterns in object-orientted development is the sing gleton pattern n. The
sin
ngleton patterrn describes hhow to ensure that there is only ever a single instance of a class in e
existence.
Typical uses of tthe singleton pattern might include the following classses:
• A database driver managger class that is responsible
e for choosing
g which databaase driver to use
u to open
a connectio
on to a databaase.
• A screen maanager class tthat is responssible for organizing the layyout of window
ws in a single screen.
• A mathema
atical class tha
at provides alg
gebraic and trrigonometric ffunctions such as sin, cos, aand tan.
JavvaScript suppo
orts the single
eton pattern, and there are
e several globaal singleton o
objects that co
ome as part
of the standard JavaScript lib
brary, such as Math and JSOON.
• The Math o object provide es mathematical functions and constantss. You access these function ns and
Math object; yyou do not create a Math o
constant vaalues directly tthrough the M object first. Th
he
following exxample showss how to acce ess some of th
he members o of the Math object:
var radiu
us = 100 * M
Math.random();
var circu
umference = 2 * Math.PI * radius;
var area = Math.PI * Math.pow(radius, 2);
• The JSON o object providees methods foor converting values to Java aScript Objectt Notation (JSSON)
strings, and
d for convertin
ng JSON string
gs back to vallues. The follo
owing example e shows how to use the
JSON objecct:
var anObj
ject;
...
var anObj
jectAsJsonSt
tring = JSON.stringify(a
anObject);
var anObj
jectAgain = JSON.parse(anObjectAsJs
sonString);
JavvaScript also p
provides a sett of global com
mmon functio ons and prope erties that can
n be used with
h all the
bu
uilt-in JavaScript objects, such as parseIn nt(), parseFlo
oat(), and isNa owing example shows
an(). The follo
ho
ow to use thesse global funcctions:
var ageEn
nteredByUser
r;
var heigh
htEnteredByU
User;
…
Programming in HTML5 with JavaScript and CSS3 7-9
Note: The JavaScript global functions are actually functions belonging to the Global
object. This is another singleton object. The functions of the Global object are intrinsic to
JavaScript, and you do not need to qualify them with Global.
7-10 Creatingg Objects and Methods by Using JavaSccript
Lesson 2
Creatiing Cusstom Objects
In addition to th
he built-in JavvaScript objeccts such as Strring, Date, Ma
ath, JSON, an nd RegExp, yo ou can also
cre
eate your own n custom obje ects. For each object, you caan specify thee properties th
hat the objectt needs to
hoold, and the fu
unctionality th
hat the object needs to imp plement.
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
C
Creating S
Simple Ob
bjects
var emp
ployee1 = new Object();
This statemen
T nt creates an oobject with no
o properties and very limiteed functionalitty (it only hass the methodss
p
provided by the Object typ pe), and assigns the object to a variable named emplo oyee1. You caan use the
e
employee1 vvariable to acccess the object.
var e
employee2 = {};
A
Adding Pro
operties to an Object
Empty objectss are not veryy useful, so JavvaScript enablles you to add
E d properties to
o an object byy using the
f
following synttax:
objectR
Reference.propertyName = value;
employe
ee1.name = "John Smith";
employe
ee1.age = 21;
employe
ee1.salary = 10000;
employe
ee1.payRise = function(a
amount) {
// Inside a method, "this"
" means the current object.
this.salary += amount;
ret
turn this.salary;
}
7-12 Creating Objects and Methods by Using JavaScript
Note: JavaScript does not support overloaded functions. This is because JavaScript has no
notion of function signatures. If you define a function for an object that has the same name as an
existing function, the new function will replace the existing function. The situation is analogous to
assigning a new value to a data property; the old value is overwritten with the new value.
objectReference.propertyName = value;
objectReference.functionName(parameters);
The following example shows how to access data properties and invoke methods on an employee object:
U
Using Objject Literaal Notation
var obj
jectName = {
pro
operty1: value1,
pro
operty2: value2,
...
};
var emp
ployee1 = {
nam
me: "John Smith",
age
e: 21,
salary: 10000
};
var emp
ployee2 = {
nam
me: "Mary Jones",
age
e: 42,
salary: 20000,
pay
yRise: function(amount) {
this.salary += amount;
return this.salary;
},
dis
splayDetails: function()
) {
alert(this.name + " is
s " + this.a
age + " and earns " + th
his.salary);
}
};
7-14 Creatingg Objects and Methods by Using JavaSccript
Ussing Consstructors
var Accou
unt = function (id, name) {
this.
.id = id;
this.
.name = name
e;
this.
.balance = 0
0;
this.
.numTransact
tions = 0;
};
3. It assigns th
his to refer to the new obje
ect.
4. It invokes th
he code in the properties on the object.
e constructor function on tthe new objecct, to set the p
The following exxample createes two Account objects and sets their prroperties. Afte
er these statem
ments,
acc1.constructo or and acc2.cconstructor p
point to the A
Account consttructor functio on.
U
Using Pro
ototypes
Constructors aare just functiions that create new objectts. If you use tthe same consstructor to cre
C eate two
o
objects, each object gets its own set of p properties as ddefined by the e constructor function. Wh hile this is
u
useful for dataa properties, the
t same mecchanism is nott quite so useful for metho ods; each object gets its
o
own copy of tthe methods defined
d by the constructor,, despite the ffact that they are logically aall the same
p
piece of code, and each copy of the metthod occupiess its own spacce in memory and has a corrresponding
m
management overhead. It iis clearly wastteful of resourrces if you cre
eate hundredss or thousandss of instances
o an object b
of by using the sa ame construcctor.
Account
t.prototype = {
dep
posit: function(amount) {
this.balance += amount
t;
this.numTransactions++
+;
},
wit
thdraw: function(amount)
) {
this.balance -= amount
t;
this.numTransactions++
+;
},
dis
splayDetails: function()
) {
alert(this.id + ", " +
this.name + " ba
alance $" +
this.balance + " (" +
this.numTransact
tions + " trransactions)");
7-16 Creating Objects and Methods by Using JavaScript
}
};
When you create an object by using a constructor function, the new object delegates functionality to the
prototype property of the constructor function. What this means is that the new object has access to all
of the properties defined in the constructor function and all of the properties defined by the prototype for
the constructor function. However, the properties defined by the prototype are shared by all instances of
the object. All objects created by using a constructor function have their own set of properties that are
defined by the constructor function, but they share the properties defined by the prototype with all other
objects created by using the same constructor function. So, you can define shared functionality such as
methods by using a prototype, and this functionality will not be duplicated. You can use the same feature
to implement shared data properties (similar to static or class properties in other object-oriented
languages).
The following example creates some objects by using the Account constructor function, and illustrates
how you can invoke the methods defined in the prototype object of the Account constructor function.
The important point to realize is that the data properties defined in the Account constructor (id, name,
balance, and numtransactions) are specific to each object (acc1 and acc2), whereas the methods
defined by the prototype (deposit, display, and withdraw) are shared by all instances. The this object
used by these functions references the appropriate instance:
U
Using the
e Object.crreate Method
Object.create(prototypeObject, properties
sObject)
var obj
j1 = Object.create(null, { prop1 = "hello", prop2 = "world
d" });
T next exam
The mple creates aan object by u
using the prottotype of the A
Account consstructor functtion:
// Acco
ount constructor functio
on, same as before.
var Acc
count = function (id, na
ame) { … };
// Acco
ount prototype, same as before.
Account
t.prototype = { ... };
// Crea
ate an object by using t
the Account prototype.
var obj
j2 = Object.create(Objec
ct.getProtottypeOf(Account));
7-18 Creatingg Objects and Methods by Using JavaSccript
Lesson 3
Extend
ding Objects
Deespite the lackk of classes in JavaScript, it is possible to implement object-oriented d features succh as
heritance and encapsulation. The concep
inh pts are similarr to those in class-based lan nguages such as C#,
Javva, and C++, but the underrlying languag ge mechanism ms are quite d different. In this lesson, you will learn
hoow JavaScript implements in nheritance and encapsulation.
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
• Implement encapsulation
n in JavaScript.
• Implement inheritance in
n JavaScript.
• Add functio
onality to existting native ob
bjects.
Programming in HTTML5 with JavaScrippt and CSS3 7-19
9
I
Implemen
nting Enca
apsulation
n
Encapsulation
E n is an importa ant principle in
i object-oriented develop
pment; it shield
ds external co
ode from the
i
internal on helps to make code simpler, more sellf-contained, aand
workiings of a classs. Encapsulatio
m
maintainable by reducing d dependenciess on other classses.
Classic object-oriented lang
C guages have keywords
k such as public, p
protected, and private thaat specify the
a
accessibility o
of members in ot have these keywords, but instead usess a technique
n a class. JavaSScript does no
k
known as clossures to achievve encapsulattion.
Closures enab
C ble you to deffine encapsula
ated variables for an objectt, and expose the variables through a sett
o public acce
of essor functions. To implemeent closures, d
define a consttructor functio
on and add thhe following
c
code:
1
1. Declare vvariables witho
out using the this keyword. The absence e of the this kkeyword mean
ns that the
variables have local sco
ope, and are vvisible only inside the consttructor functio
on.
2
2. Declare m
methods to ge
et and set the values of the e variables. Use
e the this keyyword when d
declaring
these methods to ensu
ure they are viisible to external code.
U
Using Closurres to Achieve Encapsulattion
var Person = function(
(name, age)
{
// Private propeerties.
var _
_name, _age;;
// Public methodds defined in the constructor have access to p
private properties.
this.getName = ffunction()
{
return _
_name;
}
this.setName = ffunction(nam
me)
{
_name = nam
me;
}
this.getAge = fuunction()
{
7-20 Creating Objects and Methods by Using JavaScript
return _age;
}
this.setAge = function(age)
{
if (age > 0 && age < 100)
_age = age;
}
// Constructor logic.
_name = name;
this.setAge(age);
}
// Public methods defined in the prototype do not have access to private properties.
Car.prototype =
{
toString: function()
{
return this.getName() + " is " + this.getAge();
}
}
// External code.
var person1 = new Person("Joe", 21);
alert(person1.toString()); // Displays "Joe is 21"
alert(person1._name); // Displays "undefined"
I
Implemen
nting Inhe
eritance by
y Chaining
g Prototy
ypes
IIn class-based
d languages suuch as C#, Javva, and C++, yyou implemen nt inheritance
e by defining a class that
e
extends ning an object that extendss
from an existing class. In JavaScript, you implement inherittance by defin
a existing ob
an bject.
You can use several
Y s JavaScript languagee mechanisms to implement inheritance. You can use the
O
Object.createe function to implement a form of inherritance that su
upports shared d functions an
nd instance
d
data. Anotherr common app proach that gives you more e refined conttrol over the iinheritance mechanism
m is
t make use o
to of constructorr function prototypes, as fo
ollows:
1
1. Define the base constrructor and pro
ototype.
2
2. Define the derived con
nstructor.
3
3. Set the prototype pro operty of the d
derived constrructor to be aan instance of the base obje
ect. This
ensures that the derive
ed object has access to all tthe members defined in the e base prototyype.
4
4. Reset the
e constructor property in the derived prrototype so th
hat it refers ba
ack to the derived
constructtor.
I
Implementin
ng Inheritancce by Using P
Prototype Cha
aining
// Base con
nstructor.
var Person = function(
(name, age) {
this.na
ame = name;
this.ag
ge = age;
}
// Base pro
ototype.
Person.prot
totype = {
haveBir
rthday: funcction() {
this
s.age++;
7-22 Creating Objects and Methods by Using JavaScript
}
};
// Derived constructor.
var Student = function(name, age, subject) {
this.name = name;
this.age = age;
this.subject = subject;
}
// Set the derived prototype to be the same object as the base prototype,
// and reset that derived prototype so that it uses the correct constructor.
Student.prototype = new Person();
Student.prototype.constructor = Student;
// Create a derived object and invoke any methods defined in the object or one of its
// parents. JavaScript uses prototype chaining to locate methods up the inheritance tree.
var aStudent = new Student("Jim", 20, "Physics");
aStudent.subject = "BioChemistry";
aStudent.haveBirthday();
Programming in HTTML5 with JavaScrippt and CSS3 7-23
3
A
Adding Fu
unctionaliity to Existing Obje
ects
T extend the
To e functionalityy of an object,, follow these steps:
• Get the p
prototype for an
a object.
• Assign a new
n propertyy to the objectt, to representt the new featture that you want to add.
Note: B
Be careful not to accidentally replace a fu
unction in a prototype
p with
h another funcction
w the same
with e name; this can lead to unexpected beh havior elsewheere in your ap
pplication.
A
Adding Funcctionality to a
an Object
var Point = function(x
x, y) {
this.x = x;
this.y = y;
}
Point.proto
otype.moveBy
y = function(deltaX, del
ltaY) {
this.x += deltaX;
this.y += deltaY;
}
Point.proto
otype.moveTo
o = function(otherPoint)
) {
this.x = otherPoinnt.x;
this.y = otherPoinnt.y;
}
var p1= new
w Point(100, 200);
p1.moveBy(1
10, 20);
var p2= new
w Point(25, 50);
p2.moveTo(p
p1);
7-24 Creatingg Objects and Methods by Using JavaSccript
Lab: R
Refining
g Code for Ma
aintaina
ability a
and Exttensibility
Sccenario
The existing JavvaScript code ffor the ContoosoConf websiite has been written
w withou ut much high--level
strructure or organization. Wh oach is fine for small piecess of code, it will not scale up for a
hile this appro
larrger project. A
An unstructure
ed collection oof functions aand variables scattered
s throoughout a JavvaScript file
can quickly beco ome unmainttainable.
efore impleme
Be enting more w website features by using JaavaScript, you decide to reffactor the exissting code
to introduce bettter organizattional practice ng code will b
es. The resultin ntainable and provide a
be more main
go
ood pattern fo
or implementing future web bsite features..
Ob
bjectives
Aftter completing this lab, you
u will be able to:
The following example uses Object.inherit to define a Circle prototype. This prototype is then used to
create a circle object.
The initialize function is similar to a constructor in other object-oriented languages such as C# and Java;
it initializes the state of a new object, often based on the parameters passed to it.
The inherit function has been partially defined, but the JavaScript file containing it needs completing.
Next, you will prevent variables from leaking into global scope by using an immediately invoked function
expression.
Then, you will switch the JavaScript code into strict mode. And finally, you will attach the inherit function
to the built-in JavaScript Object object.
2. Start the 20480A-SEA-DEV11-07 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 1
folder.
• You will implement the inherit function, using the TODO comments as guidance.
7-26 Creating Objects and Methods by Using JavaScript
• copyOwnProperties is a helper function that copies properties from one object to another. The
inherit function will use this function.
• Create and assign a variable named factory by using the Object.create function. Specify the current
object as the prototype.
• Add a method called create to factory. Leave the body of the method empty for now; you will
implement it in the next step.
3. At the end of the JavaScript file, make the inherit function available to other scripts by attaching it to
the built-in Object object.
Results: After completing this exercise, you will have written the Object.inherit utility function that you
will use in later exercises to structure the code for the web application. You will also have modified the
scope for this function, and specified that the code should run by using strict mode.
Programming in HTML5 with JavaScript and CSS3 7-27
2. In the schedule.js file, in the scripts\pages folder, find the following comment:
// TODO: Create a ScheduleList factory object using the Object.inherit helper method.
3. After this comment, use the Object.inherit function to create an object named ScheduleList.
4. Add an initialize function to the object passed to Object.inherit. The initialize function should take
two parameters called element and localStarStorage and use them to create properties also called
element and localStarStorage for the ScheduleList object.
5. Remove the element and localStarStorage variables from the ScheduleList object (they have been
replaced by the properties that you just defined).
2. Convert each of the functions following the comment into methods of ScheduleList.
Note: Thiss step ensuress that the corrrect object is made the con
ntext of the ajax callbacks
tha
at occur when
n downloading is complete e.
4. In the addA
All function, specify that the forEach funnction should call the add method of the object
referenced by this. Also, pass this as tthe second pa he forEach function.
arameter to th
Note: The e second parameter to the forEach function specifies the object that any use of
this will reference in the add
d function.
X Task 4: Te
est the Appllication
1. Run the app
plication and view the sche
edule.htm pa
age.
Note: The styling and layout of the Schedule page has been changed. This is performed by
using the CSS rules implemented in the schedule.css style sheet and is not a result of any updates
made to the JavaScript code.
Results: After completing this exercise, you will have refactored the JavaScript code for the Schedule page
to be more maintainable by using objects.
7-30 Creatingg Objects and Methods by Using JavaSccript
Modu
ule Reviiew and
d Takea
aways
M
Module Revie
ew
In this module, yyou have seen n how to follo
ow an object-oriented apprroach to application design n in
JavvaScript. First, you learned how to minim ame clashes by using name
mize global na espaces, strict mode, and
immediate funcctions. Next, yo ou saw how to create custoom objects byy using objectt literal syntaxx,
constructors, an nd prototypes. Finally, you saw
s how to im
mplement enccapsulation an nd inheritance e in
JavvaScript.
Question: How
H can you guard againsst name clashe
es in JavaScrip
pt?
Ve
erify the correcctness of the statement by placing a maark in the column to the rig
ght.
S
Statement Answer
IIf you modify the prototype object for a constructor ffunction, the changes
c
a only visiblle to new obje
are ects that you create by usin
ng that constrructor
f
function; existting objects created by usin
ng the construuctor functionn will be
u
unaffected. Trrue or False?
Q
Question
W
Which of the ffollowing statements is tru
ue?
S
Select the corrrect answer.
Question
Module 8
Creating Interactive Pages by Using HTML5 APIs
Contents:
Module Overview 8-2
Modu
ule Ove
erview
Intteractivity is a key aspect off modern web b applicationss, enabling you to build com
mpelling web sites that
can quickly resp user, and also adapt themselves to the u
pond to the acctions of the u user's location.
Ob
bjectives
Aftter completing this module
e, you will be able to:
• Access the local file syste
em, and add drag-and-drop
d p support to web
w pages.
• Obtain info
ormation abou
ut the current location of th
he user.
• Use the F12
2 Developer T
Tools in Internet Explorer to
o debug and p
profile a web application.
Programming in HTML5 with JavaScrript and CSS3 8-3
3
Lesson 1
Interracting with Fiiles
HTML5 enable
H es a web application to interact with the
e local file systtem, and supp
ports drag-an nd-drop
o
operations thaat enable the user to drag files or HTMLL elements ontto a web page e. In this lesso
on, you will
l
learn how to use
u the HTMLL5 File APIs an nd how to add d drag-and-drop support to a web page e.
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Use FileR
Reader to read
d a binary file
e.
• Add drag
g-and-drop su
upport to a we
eb page.
8-4 Creating Interactive Pages byy Using HTML5 APIss
HT
TML5 File
e Interface
es
• A Blob inteerface represents immutable raw data. A Blob has a ty ype attribute that indicatess the media
type of the data, such as "text/plain"". Blob also an e() method thaat returns a portion of a
nd has a slice
Blob betwe een a specifiedd start and en
nd offset. Slicin
ng a blob is u
useful if you w
want to uploadd a large
file increme
entally to a server.
• The File intterface inheritts from Blob, and representts an individual file. A File has two addittional read-
utes that descrribe the state of the file:
only attribu
• The FileListt interface is a collection off File objects. There are two
o common wa
ays to obtain a FileList
object in a w
web page:
• Define an <
<input type= ="file"> element in your we eb page, and handle the ch
hange event. The
change eveent indicates tthe files that tthe user selectted in the element.
• The FileRea
ader interface
e enables an application
a to read a file orr blob into a JaavaScript variable.
Programming in HTML5 with JavaScrript and CSS3 8-5
5
T FileRe
The eader Inte
erface
T FileReader interface p
The e methods for reading data:
provides three
• readAsDataURL() reads a file or blo ob and makess the contentss available as a data URL. This method iss
useful if yyou want to re
ead the conte
ents of a binarry file, such ass an image.
• readAsArrayBuffer() reads a file orr blob and maakes the conte ents available as an ArrayB
Buffer. An
ArrayBufffer representts a finite nummber of bytes that can be u
used to store n numbers of an
ny size, such
as an arraay of 8-bit inte
egers or 32-b
bit floating point numbers.
• The prog
gress event occcurs repeated
dly while data
a is being load
ded, to indicatte progress.
• The load event indicattes that the daata has been successfully
s lo
oaded. The filee contents aree available
through tthe result attrribute on the FileReader o
object. The ressult is a Blob o
object if you iinvoked
readAsTe ext() or readAAsDataURL()), or an ArrayBuffer objectt if you invoke ed readAsArrrayBuffer().
Re
eading a T
Text File
The FileReaderr readAsText(() method ena ables you to rread a text file
e on the local file system. The
folllowing examp
ple shows how
w to read a te
ext file.
The web page in ncludes an <iinput> eleme ent that enables the user to
o select a text file on the loccal file
sysstem. As soonn as the user hhas selected th
he file, the on
nLoadTextFilee() function reeads the file aand displays
its contents as plain
p text in a <textArea> element on the web page.
Re
eading a Textt File
<
<input type="file" id="ttheTextFile" onchange="o
onLoadTextFi
ile()" />
<
<textArea id=
="theMessageeArea" rows=
="30" cols="4
40"></textAr
rea>
<
<script type=
="text/javasscript">
function onLoadTextFFile() {
var t
theFileElem = document.getElementByyId("theText
tFile");
// Ge
et the File object seleected by the user, and m
make sure it
t is a text f
file.
if (t
theFileElem..files.lengt
th != 0 && th
heFileElem.f
files[0].typ
pe.match(/tex
xt.*/)) {
/
// Create a FileReader and handle tthe onload a
and onerror events.
v
var reader = new FileReeader();
reader.onloaad = functio
on(e){
var theM
MessageAreaE
Elem = docume
ent.getEleme
entById("the
eMessageArea");
theMessa
ageAreaElem.value = e.ta
arget.result
t;
}
};
reader.onerrror = function(e){
alert("C
Cannot load text file");
}
};
/
// Read textt file (the second param
meter is opt
tional - the
e default enc
coding is
"UTF-8").
reader.readAAsText(theFileElem.files
s[0], "ISO-8
8859-1");
} els
se {
a
alert("Pleasse select a text file");
}
}
<
</script>
Programming in HTML5 with JavaScrript and CSS3 8-7
7
R
Reading a Binary Fiile
R
Reading a Binary File
<input type
e="file" id=="theBinaryFile" onchang
ge="onLoadBinaryFile()" />
<img id="th
heImage"></img>
<script typ
pe="text/javvascript">
functio
on onLoadBinnaryFile() {
var
r theFileEleem = document.getElement
tById("theBinaryFile");
// Get the File object selected by thhe user (andd make sure it is an ima
age file).
if (theFileEleem.files.length != 0 && theFileElemm.files[0].type.match(/i
image.*/))
{
// Create a FileReader and handlee the onloadd and onerror events.
var readerr = new FileReader();
reader.onload = function(e){
var th
heImgElem = document.get
tElementByIdd("theImage");
theImg
gElem.src = e.target.res
sult;
};
reader.oneerror = function(e){
alert(
("Cannot load binary fil
le");
};
// Read thhe binary file.
reader.reaadAsDataURL(theFileElem.
.files[0]);
} e
else {
alert("Pleease select a binary fil
le");
}
}
</script>
8-8 Creating Interactive Pages byy Using HTML5 APIss
Im
mplementing Drag--and-Drop
p
HT
TML5 supportts drag-and-drop. You can drag elementts on a web paage or files in the file system, and
op them on another eleme
dro ent in the web
b page.
To
o make an elem
ment draggab
ble, follow the
ese steps:
• In the drag
gstart event handler functio
on, configure data transfer information ffor the drag-aand-drop
operation. Y
You can do thhis through th
he dataTransffer attribute o object, which represents
on the event o
a DataTrannsfer object.
• wed restricts w
effectAllow what type of d op operation is allowed, succh as copy, m
drag-and-dro move, or
link.
• dropEffectt specifies the feedback thaat the user recceives when th
he mouse hovvers over a tarrget
element. Th
he dropEffectt attribute cann be none, co opy, move, orr link.
Ma
aking a <div
v> Element D
Draggable
<
<div draggabl
le="true" on
ndrag="handleDrag()">
<b>Some c
content</b> to be dragg
ged.
<
</div>
<
<script type=
="text/javas
script">
function handleDrag(
(event) {
event
t.dataTransf
fer.effectAllowed = "cop
py";
event
t.dataTransf
fer.setData(
("text/html", event.targ
get.innerHTM
ML);
}
<
</script>
Programming in HTML5 with JavaScript and CSS3 8-9
HTML5 elements cannot accept dropped data by default. To enable an element to accept dropped data,
you must disable the default behavior, as follows:
• In the dragover event handler function, invoke the preventDefault() method on the object that
raised the event.
When the user drops data on a target element, the drop event occurs. To accept the data being dropped
on the element, do this:
• In the drop event handler function, get the data being dropped by invoking the getData() method
on the dataTransfer attribute of the object that raised the event.
The following example shows how to make a <div> element accept HTML content being dropped on it.
Lesson 2
Incorp
porating Multtimedia
In this lesson, yo
ou will learn hhow to use the
e <video> an nd <audio> ttags in HTML5
5 to play video
o and
audio multimed dia files withou
ut the need fo
or plugins (natively).
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
• ow to play vid
Describe ho deo files.
• Support mu
ultiple video formats.
f
P
Playing Video Conttent by Ussing the <
<video> T
Tag
HTML5 provid
H des a <video> > tag that ena ables you to pplay video in a web page, without
w the ne
eed for
p
plugins (natively). The ability to play videeo natively is especially ben
neficial in mobile and smarrtphone
p
platforms, where some plugins are not supported.
s
The simplest w
T way to use the
e <video> taag is to set the
e src attribute
e to the video that you wan
nt to play. For
e
example:
<video src="MyVideo.mp4"></vid
deo>
• The controls Boolean attribute speccifies that the video player should displa
ay video contrrol buttons
such as Play, Pause, an
nd Mute.
• The auto
oplay Booleann attribute spe
ecifies that the utomatically as soon as the
e video will staart playing au
video con
ntent has been loaded.
S
Supportin
ng Multiplle Video FFormats
The HTML5 sp
T pecification does not stipullate what vide
eo formats are
e supported b
by web browse
ers. For
e
example, mosst browsers suupport the .mpp4 format, somme browsers ssupport the .w
webm format,, while some
s
support the .o
ogv format.
FFor maximumm portability, you
y can provid erent formats, so that the
de several verrsions of your video in diffe
v
video can be played successsfully on diffe
erent browserrs. To support multiple vide eo formats, include one or
m
more <sourcee> tags within the <video> tag. The <ssource> tag h has two attributes:
S
Supporting M
Multiple Form
mats in a Vid
deo Player
<video post
ter="MyPoste
er.jpg" autoplay control
ls>
<source
e src="MyVid
deos/MyVideo.mp4" type=='video/mp4' />
<source
e src="MyVid
deos/MyVideo.webm" type=
='video/webm
m' />
<source
e src="MyVid
deos/MyVideo.ogv" type=='video/ogg' />
<!-- Yo
ou can embed
d Flash or Silverlight c
content here
e, as a fallback -->
<!-- Yo
ou can also display some simple tex
xt in case the
t browser does not suppport the
video tag -
-->
Cannot play video. Download video <a href
f="MyVideos/
/MyVideo.webm">here</a>
</video>
8-14 Creatingg Interactive Pages by Using HTML5 APPIs
In
nteracting with Vide
eo in JavaaScript Cod
de
Creating a Vide
eo Player by Using JavaScript Code
f
function crea
ateVideoElem
ment(nameOfV
VideoFile, na
ameOfHostEle
ement) {
// Create
e a video ob
bject and se
et its properties.
var newVi
ideo = docum
ment.createE
Element("vide
eo");
newVideo.src = nameO
OfVideo;
newVideo.loop = true
e;
newVideo.autoplay = true;
newVideo.controls = true;
newVideo.poster = "I
ImageLoading
g.png";
// Add th
he video obj
ject to an e
existing elem
ment on the web page.
var hostE
Elem = docum
ment.getElem
mentById("vid
deoDir");
hostElem.appendChild
d(newVideo);
}
The video objecct has propertties and functtions that enable you to control video pllayback
pro
ogrammatically:
• on property g
The duratio gets the total d
duration of th
he video.
• The volume
e property ge
ets and sets th
he volume of the
t video.
Playing a Video
if (aVideo.paused) {
alert("Video current time: " + aVideo.currentTime + ", total duration: " +
aVideo.duration);
aVideo.play();
}
else {
aVideo.pause();
}
The video object has events that enable you to check whether content is available, to check the state of
video playback, and to monitor the current playing position in a video. The following list describes some
common events:
• The loadedmetadata event fires when the video object gets enough information about the content
to know the duration. The event handler function can read the duration property on the video
object, to tell the user the duration of the video.
• The loadeddata event fires when the all video data has been loaded. The event handler function can
then invoke the play() function on the video object, in order to play the video.
• The timeupdate event fires during playback of a video, to indicate the current time. The event
handler function can read the currentTime property on the video object, to tell the user the current
time in the video.
The following example shows how to handle the loadedmetadata, loadeddata, and timeupdate events
on a video object.
Pllaying Aud
dio Conte
ent by Using the <aaudio> Tag
The simplest wa
ay to use the <
<audio> tag is to set the src
s attribute to
o the audio file that you waant to play:
<audio sr
rc="MyAudio.mp3"</audio>
>
Yo
ou can also plaay audio by using JavaScrip
pt code. The technique is ve
ery similar to that for playin
ng video.
The <audio> taag has many aattributes in ccommon with the <video> tag, including:
• controls
• autoplay
• loop
• The audio o
object has pla
ay() and pausse() functionss, to play or paause the audio playback.
• The audio o
object has pro
operties to co
ontrol playbacck, such as con
ntrols, autop
play, loop, pau
used,
currentTim
me, duration, volume, mutted, and play ybackRate.
• The audio o
object has eve
ents to indicate progress of playback, su
uch as loadedmetadata, lo
oadeddata,
and timeuppdate.
Programming in HTTML5 with JavaScrippt and CSS3 8-17
7
Lesson 3
Reacting to
o Browsser Loca
ation an
nd Context
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Request g
geolocation in
nformation.
• Process g
geolocation information.
• Detect th
he network and execution ccontext for a p
page.
8-18 Creatingg Interactive Pages by Using HTML5 APPIs
Th
he HTML5
5 Geolocation API
Location awarenness is a key feature in manny web applications, especiially on mobile devices andd
sm
martphones. Thhe HTML5 Ge eolocation API enables a weeb application
n to detect thee current loca
ation of the
de
evice, expresse
ed in longitud
de, latitude, an
nd altitude.
Typical uses of tthe Geolocatio
on API include:
• Locating the current possition of the user, and giving instructionss on how to get to a new lo
ocation.
R
Requestin
ng Geolocation Info
ormation
T HTML5 G
The Geolocation AP
PI supports tw
wo types of po
osition requesst:
T getCurre
The entPosition() and watchPo
osition() methods take the
e following pa
arameters:
• An option
nal error call-back function
n, which will be called by th
he browser if aany errors occcur.
• An option
nal PositionO Options objecct, which enabbles you to configure the ge
eolocation req
quest. You
can specify the following propertiess on the PosittionOptions oobject:
o bleHighAccurracy. A Booleaan property that gives a hint that you want the device
enab e to use the
hnique to obttain geolocation informatio
mostt accurate tech on. The default value for the
enab
bleHighAccurracy propertyy is false.
o timeeout. The maxximum elapsed d time in milliiseconds that the browser is i permitted to get
locattion data. If daata is not avaiilable in this tiime, the errorr call-back fun
nction is called
d. The defaultt
valuee for the time eout property is infinity.
navigator.geolocation.getCurrentPosition(myPositionCallbackFunction,
myPositionErrorCallbackFunction,
{enableHighAccuracy: true, timeout: 5000} );
The following example shows how to make repeated requests for geolocation information. The example
requests the highest accuracy information available, and specifies that the data can be up to 10 seconds
old before it must be refreshed by the browser.
myPositionErrorCallbackFunction,
navigator.geolocation.clearWatch(watchID);
Programming in HTTML5 with JavaScrippt and CSS3 8-21
1
P
Processing
g Geoloca
ation Information
• altitudeA
Accuracy, in m
meters.
• heading, in degrees re
elative to the North directio
on.
• speed, in
n meters/secon
nd.
P
Processing G
Geolocation Information
functio
on myPositio
onCallbackFunction(posittion) {
var
r latitude = position.coords.latit tude;
var
r longitude = position.coords.longiitude;
var
r accuracy = position.coords.accur racy;
var
r heading = position.coords.headi
ing;
var
r speed = position.coords.speed
d;
var
r altitude = position.coords.altit tude;
var
r altitudeAc
ccuracy = position.coor rds.altitude
eAccuracy;
// Add code he
ere, to process the infoormation.
}
8-22 Creatingg Interactive Pages by Using HTML5 APPIs
Handling G
Geolocatio
on Errors
If a geolocation error occurs, the browser calls the errorr call-back funnction that yo
ou specified w
when you
invvoked getCurrrentPositionn() or watchPPosition(). The eceives an errror object
e error call-baack function re
thaat has the following properrties:
• code: The e
error code can
n be one of th
he following values:
v Positio
onError.PERM
MISSION_DEN
NIED,
PositionErrror.POSITIONN_UNAVAILA ABLE, or PosittionError.TIM
MEOUT.
Ha ocation Errors
andling Geolo
f
function posi
itionErrorCa
allback(erro
or) {
var errorMessage = e
error.messag
ge;
var errorCode = erro
or.code;
// Add co
ode here, to
o process th
he informatio
on.
}
Programming in HTTML5 with JavaScrippt and CSS3 8-23
3
D
Detecting
g the Conttext for a Page
HTML5 provid
H des the Page Visibility
V API tthat enables you
y to determmine if a web p
page is currenntly visible.
D
Depending on
n whether a p
page is visible or not, you caan choose to modify its behavior. For exxample:
• If a web-b
based puzzle game is hidde
en, the game could be pau
used until it be
ecomes visible
e again.
• The docu
ument.visibiliityState prop
perty indicatess the detailed page visibilityy state, such aas
PAGE_VISIBLE or PAGGE_PREVIEW.
• The visib
bilitychange e
event fires anyy time the visiibility state off the page chaanges.
HTML5 also e
H enables a browwser to determmine if it has a live networkk connection. You can use tthis
i
information to
o modify the appearance o of a web page e, in order to g
give the user visual
v feedbacck about
w
whether the user
u is online or
o offline. To determine wh hether the bro e or offline, use the
owser is online
f
following properties and evvents:
• The navig
gator.onLine
e property, wh
hich indicates whether the browser
b is online or offline.
• The onlin
ne event, whicch fires when the browser w
was offline and becomes on
nline.
• The offlin
ne event, whicch fires when the browser w
was online an
nd becomes offline.
HTML5 enable
H es a web application to dettermine the b
browser type, aalso common nly known as tthe user
a
agent. You can use this info
ormation to access JavaScript or HTML ffeatures that aare only suppo orted on a
p
particular type
e or version o
of browser. To
o determine th
he user agent,, use the following propertyy:
• The naviggator.userAg
gent propertyy, which returnns a string ind
dicating the usser agent strin
ng for the
browser. You can then use the string
g indexof() fu
unction to tesst for a particu
ular browser ttype.
8-24 Creatingg Interactive Pages by Using HTML5 APPIs
Lesson 4
Debug
gging a
and Pro
ofiling a Web A
Applica
ation
Vissual Studio 20012 provides a large numbe er of debuggiing and profiling tools, butt you can perfform many
sim
milar tasks for a live web appplication by uusing the F12 Developer To ools provided with Internett Explorer.
In this lesson, yo
ou will also leaarn how to usse these tools to profile the
e performancee of HTML5 wweb pages,
and to debug JaavaScript code e.
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to describ
be how to use the HTML5 A APIs and Intern
net
Explorer 10 Devveloper Tools to debug Java a Script code and to profile
e the performance of web pages.
p
Programming in HTTML5 with JavaScrippt and CSS3 8-25
5
O
Overview of the F12 Develop
per Tools in Interne
et Explore
er 10
Download spe
D eed for web aapplications caan be a critica
al factor in use
er satisfaction. Even a relatiively small
d
delay of a few
w hundred millliseconds cann be unacceptable for some e users. HTMLL5 provides the Navigation
T
Timing API thhat enables yo
ou to determin ne the downlo oad speed of yyour web app plications. To use the
N
Navigation Timing API, usee the followingg properties oon the window w.performan nce object:
• navigatio
on: indicates how
h the user navigated to the page.
• timing: p
provides data for navigation
n and page lo
oad events.
Additio
onal Reading: For more infformation aboout the timing
g data availab
ble in the
window.perfformance.tim
w ming object, se
ee http://go.m m/fwlink/?LinkID=267732.
microsoft.com
Another usefu
A ul technique ffor developerss is to use the console.log(() function to write status information
t the browse
to er console. Wrriting status in
nformation to the console ccan be a helpfful way of traccing the path
t
through a web application,, and can alsoo help you to diagnose
d poteential problemms in the codee. To view the
e
c
console windo
ow in Internett Explorer 10, follow these ssteps:
• Press F12
2, or click the T
Tools icon an
nd then click F
F12 Develope
er Tools.
• In the De
eveloper Toolss panel, click tthe Console menu
m item.
The Develope
T er Tools capab
bilities in Interrnet Explorer 10
1 provide a wide
w range off useful featurres for
d
developers, in
ncluding:
• Exploring
g HTML docum
ment structure
e.
• Determin
ning which CSS styles applyy to elements in the document.
• Debuggin
ng JavaScript code.
• Profiling application pe
erformance.
• Observing
g network com
mmunicationss.
8-26 Creatingg Interactive Pages by Using HTML5 APPIs
Demonstration: Usin
ng the F12
2 Develop
per Tools to
t Debug JavaScrip
pt Code
De
emonstration Steps
Sett a Breakpoint in JavaScriptt code
2. On the Win
ndows taskbarr, click Interne
et Explorer.
6. On the Too
ols menu, clickk F12 developer tools.
7. If the F12 D
Developer Too ppears as a pane in Internett Explorer, in tthe F12 Developer Tools
ols window ap
pane, click Unpin.
9. Click in the margin next to line 12, in o nt on the firstt statement inside the
order to creatte a breakpoin
onload() fu unction.
Programming in HTTML5 with JavaScrippt and CSS3 8-27
7
The Scrip
pt window sho
ould look like this:
FIGUR
RE 8.1: THE SC
CRIPT WINDO
OW WITH A BREAKPOINT SET
S
Step Through
h JavaScript Co
ode and Exam
mine Variabless
1
1. On the F1
12 Developer Tools toolbarr, click Start d
debugging.
2
2. In the F12
2 Developer Tools
T window,, verify that th
he debugger p
pauses executtion at the bre
eakpoint.
3
3. In the right pane, click the Locals ta
ab.
4
4. On the F1 12 Developer Tools toolbarr, click the Ste
ep over butto on several time
es to step thro
ough the
code. In tthe Locals tab
b, verify that the
t value of thhe i variable changes as exeecution progrresses.
5
5. Close the
e F12 Developer Tools wind
dow.
6
6. Close Inte
ernet Explorerr.
Note: YYou cannot use the F12 Devveloper Tools to debug JavvaScript code ffor a web
application th
a hat is already running
r by ussing the Visuaal Studio debu
ugger.
8-28 Creatingg Interactive Pages by Using HTML5 APPIs
Demonstration: Usin
ng the F12
2 Develop
per Tools to
t Profile a Web
pplication
Ap n
In this demonstration, you wiill see how to examine the network traffic for a web aapplication, an
nd how to
capture profiling
g information
n to enable yoou to identify the hot spots in a web app
plication.
De
emonstration Steps
Exaamine the Ne
etwork Traffic for a Web Ap
pplication
1. On the Win
ndows 8 Start screen, click the Desktop tile.
2. On the Win
ndows taskbarr, click Interne
et Explorer.
5. On the Too
ols menu, clickk F12 developer tools.
6. In the F12 D
Developer Too
ols window, click Network
k.
7. On the F12 Developer To
ools toolbar, cclick Start cap
pturing.
9. he F12 Develo
Return to th oper Tools win
ndow.
Programming in HTTML5 with JavaScrippt and CSS3 8-29
9
The netw
work traffic sho
ould look like this (the actu
ual values disp
played may vaary):
FIGUR
RE 8.2: THE NETWORK TRA
AFFIC CAPTU
URED FOR A WEB PAGE
1 Click the first line of th
10. he network capture, and the
en on the too
olbar click Go to detailed v
view.
1 Click Req
11. quest headerss.
1 Click Req
12. quest body.
1 Click Coo
15. okies.
1 Click Initiiator.
16.
1 Click Tim
17. mings.
1 On the F1
18. 12 Developer Tools toolbarr, click Stop capturing.
C
Capture Profille Data for a W
Web Application
1
1. In the F12
2 Developer Tools
T window,, click Profiler.
2
2. On the F1
12 Developer Tools toolbarr, click Start p
profiling.
3
3. In Interne
et Explorer, cliick the amaziing sites link.
4
4. Return to
o the F12 Deve
eloper Tools w
window.
5
5. On the F1
12 Developer Tools toolbarr, click Stop p
profiling.
8-30 Creatingg Interactive Pages by Using HTML5 APPIs
The capture
ed profile dataa should lookk like this:
In the captu
ured data, exaamine each caall performed by the onrea
adystatechan
nge event han
ndler.
8. Close the F1
12 Developer Tools window
w.
9. Close Intern
net Explorer.
Programming in HTTML5 with JavaScrippt and CSS3 8-31
1
Lab: Creatin
ng Interractive Pages w
with HT
TML5 A
APIs
S
Scenario
The ContosoC
T Conf organizeers want to higghlight the lattest HTML5 teechnologies in n order to creaate an
i
interactive exp
perience for p
people visiting
g the conferen he conference organizers
nce website. SSpecifically, th
h
have asked yoou to add the following feaatures to the aapplication:
O
Objectives
A
After completting this lab, you
y will be able to:
• Add video
o to an HTMLL page.
• Use a draag-and-drop o
operation to ccreate interacttive pages, an
nd to read files by using the
e File API.
• Get the lo
ocation of the
e user by using
g the Geolocaation API.
E
Estimated Tim
me: 60 minutes
• Virtual Machines: 2048
80-SEA-DEV11
1-08, MSL-TM
MG1
• User Nam
me: Student
• Password
d: Pa$$w0rd
8-32 Creating Interactive Pages by Using HTML5 APIs
You will add event listeners to handle drag-and-drop events. Then you will use the File API’s FileReader
object to read a file as a data URL, which is then displayed on the page. Finally, you will run the
application and test the Speaker Badge page.
X Task 1: Review the HTML Markup and JavaScript Code for the Speaker Badge Page
1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-08 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 1
folder.
4. Open speaker-badge.htm and review the HTML markup for this page. Notice the <img> element
that will display the speaker’s image when you have implemented the drag-and-drop functionality.
5. Also notice that the page has script references for jQuery and the /scripts/pages/speaker-badge.js
file.
6. Open the speaker-badge.js file in the scripts/pages folder, and review the JavaScript code. This
code defines a SpeakerBadgePage object that controls the page.
Note: The element variable contains a reference to the <img> element that displays the
speaker's image.
o Ensure that the array is not empty and the call isImageType to ensure the first file is a type of
image.
Note: The isImageType function checks that the file specified as the parameter is a jpeg,
jpg or png file.
Note: The readFile function is not yet complete. You will implement the missing parts of
this function in the next task.
o If a non-image file was dropped, display an alert with the following message:
2. use the File API to implement the missing functionality in the readFile method:
o In the callback, resolve the reading deferred object, passing it the result of reading the file.
o Before the readFile method returns the reading object, use the reader to start reading the file as
a data URL.
Note: Reading a file is an asynchronous operation, so the readFile method returns a jQuery
deferred object that is resolved after the file has been read.
Note: The Speaker Badge page is not accessible from the menu bar in the application
because this feature is only intended for use by speakers. To view this page, you must navigate
directly to the speaker-badge.htm page on the web site.
2. Drag-and-drop the file mark-hanson.jpg in the E:\Labfiles\Resources folder onto the Speaker
Badge page’s empty image element.
3. Verify that the speaker’s photo is displayed within the image element.
Results: After completing this exercise, you will have implemented functionality that enables the user to
drag-and-drop an image from File Explorer into the web page.
8-34 Creating Interactive Pages by Using HTML5 APIs
Programming in HTML5 with JavaScript and CSS3 8-35
3. Add a <video> element, using the video source specified in the index.htm file.
2. Also add a <span> element with the class video-time to the <div> element; you will use this span
to display the elapsed time for the video.
Note: The JavaScript code used by this page references the play, pause, and elapsed time
elements on the page by using the classes specified in this task.
3. Add a reference to the video.js script in the /scripts/pages folder to the index.htm file.
3. Near the bottom of the file, add an event listener for the loadeddata event of the video, which calls
the ready function.
o In the play method, start the video playing, hide the play button, and display the pause button.
o In the pause method, pause the video, hide the pause button, and display the play button.
8-36 Creating Interactive Pages by Using HTML5 APIs
5. Add click event listeners for the play and pause buttons, which call the play and pause functions,
respectively.
2. Use the formatTime helper function to convert the total seconds into HH:MM:SS format.
3. Add a timeupdate event listener for the video element that invokes the updateTime function.
2. Wait for the video to load and the Play button to appear.
3. Click Play, verify that the video begins to play and that the elapsed time is displayed.
Note: You will not hear any sound because the virtual machine does not support audio.
Results: After completing this exercise, you will have added a video player to the Home page.
Programming in HTML5 with JavaScript and CSS3 8-37
You will use the Geolocation API to get the visitor’s current location, and then you will calculate and
display the distance to the conference venue. Finally, you will run the application and verify that this
feature is working as expected.
2. Open the location.htm file and review the HTML. markup for this page. Notice that the page
includes the following empty heading:
<h2 id="distance"></h2>
3. You will display the distance of the user to the conference venue in this heading later in this exercise.
4. Review the JavaScript code for this page in the location.js file, and note that the conference venue
location is stored in a variable named conferenceLocation.
X Task 2: Get the Current Location of the User Viewing the Page
1. Near the end of the location.js file find the comment:
2. Use the Geolocation API to get the current location of the user viewing the file.
o Use the callback function updateUIForPosition to process the location.
Note: The updateUIForPosition function will display the distance of the user from the
conference venue. This function is not yet fully implemented; you will complete it in the next task.
• Use the callback function error to handle any errors that might occur.
Note: If Internet Explorer displays the message localhost wants to track your physical
location, click Allow once.
2. Verify that the page displays the distance to the conference venue in miles.
Results: After completing this exercise, you will have a Location page that displays the distance of the
user from the conference venue.
Programming in HTTML5 with JavaScrippt and CSS3 8-39
9
Module Rev
view an
nd Take
eaways
M
Module Rev
view
IIn this modulee, you have seeen how to usse HTML5 APIIs to access thhe local file sysstem, supportt drag-and-
d
drop data opeerations, play multimedia files natively in
n a web page,, and obtain geolocation
g in
nformation
a
about the bro
owser. You havve also learne
ed how to deb bug and profile web applicaations by usinng the F12
D
Developer Tools in Internett Explorer.
V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.
Statement Answer
HTML5 brow
wsers are guaaranteed to su
upport the .mp
p4 video form
mat. True or
false?
V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.
Statement Answer
Module 9
Adding Offline Support to Web Applications
Contents:
Module Overview 9-2
Modu
ule Ove
erview
In this module, yyou will learn how to use these technoloogies to create
e robust web applications tthat can
continue runninng even when a network co onnection is unavailable.
Ob
bjectives
Aftter completing this module
e, you will be able to:
Lesson 1
Read
ding and
d Writing Datta Locallly
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
M
Maintaining
g Session State Info
ormation by Using Cookies
A cookie
c is noth
hing more thaan a text file w
with a small nu
umber of field e used to identify the
ds that can be
useer's session. C
Cookies persistt data betweeen browser sesssions, unless the user has cconfigured th he browser
setttings to flush
h them when tthe browser closes. A good d example of tthis continuityy is the Amazoon®
weebsite, where e even if you haave not loggeed in, Amazon n can recognizze you, and pe ersonalizes yo
our pages
acccording to its analysis of yo
our interests and
a preferences. This perso onalization is aachieved by using
cookies; informa ation about a user's prefere
ences is stored he user's computer, and thiis
d locally on th
infformation is trransmitted as part of each request sent tot the Amazo on website.
Coookies can onlly store a veryy small amoun nt of data, up to 4 KB. There is an importtant reason fo
or this
lim
mitation. Cookkies are design ned to be sent to and fromm the web servver on each annd every page e request. If
theey were any b bigger, their b
bandwidth reqquirements co ould have a sig
gnificant impaact on the
ressponsiveness o of the web appplication. However, just ass the web has evolved, so has the use of cookies.
Inccreasingly, the
ey are used too store far more than just seession tokens. Cookies havee become a p place to
sto
ore important user profile d data, page hisstory, and other data.
The grave danger in keeping user data in ccookies is that information can be share ed unintentionnally (or
othherwise) betw
ween websites, and in recennt times they h have become notorious betraying your p personal
infformation without your connsent. In coun
ntries through pean Union, recent legislation forces
hout the Europ
weebsites hosted
d in these countries to notiffy a user if the
ey use cookiess, and to enab
ble the user to
o disable
theem.
An
nother issue to
o be aware off is that users o
often open se everal tabs whhen browsing a single site. T
The data
he
eld in cookies is shared betw
ween these taabs, but cookie es have no deefined synchroonization or concurrency
meechanism. This can lead to undesirable e effects if the values held in a cookie are cchanged in onne tab, and
are
e then used in
n the second ttab mid-proce ess.
Programming in HTML5 with JavaScript and CSS3 9-5
Since cookies are designed to associate a user session with a web application, they are mapped to URLs
either at the root level or a subdirectory level, and individual pages, betraying their allegiance to a time
when web servers were essentially just file servers, and applications were essentially just HTML pages in
folders. This is no longer an accurate paradigm. For example, the MVC pattern implemented by many
common web applications disassociates the physical server file structure from the URLs used to fetch
pages and other resources.
In an increasingly semantic web, cookies are becoming less useful, and clearly raise some significant
concerns if misused. Cookies were never designed to be used as a wholesale storage technology, and
HTML5 introduces new client-side storage paradigms to overcome many of shortcomings of cookies.
These technologies include the Session Storage API and the Local Storage API.
9-6 Adding Offline
O Support to Web
W Applications
Pe
ersisting S
Session Daata by Using Session Storage
e
Session storage is a browser-persistence mmechanism thaat can store te ext data on thhe device runn ning the
bro
owser. As the name impliess, data kept in
n this store lassts for the durration of the ccurrent user se
ession.
Whhen the user ccloses the bro
owser, the sesssion store is cleared automatically.
Session storage is widely supported and haas been impleemented by thhe major browwsers, includin
ng Internet
Explorer, since 2
2009. You access session sto
orage by usin
ng the session
nStorage propperty of the w
window
ob
bject. You can test whether a browser implements sesssion storage bby querying fo
or the presencce of this
pro
operty, like th
his:
if( windo
ow.sessionSt
torage ){
...
}
• getItem an nd setItem functions. The ssetItem function expects yo e the key and the data to
ou to provide
store. The getItem
g functtion uses the key
k to return the data. If th
here is no dataa with the spe
ecified key,
the value re
eturned is nulll.
sessionSt
torage.setIt
tem("key","so
ome text val
lue");
var textF
FromSession = sessionSto
orage.getIte
em("key");
• name-key p
pair. You can u
use array nota
ation, and spe
ecify the key vvalue as the array index.
sessionSt
torage["key"
"] = "some text value";
var textF
FromSession2
2 = sessionStorage["key""];
• pseudo-pro
operties. You can
c add a pro
operty for each key to the ssessionStorag
ge object.
sessionSt
torage.key = "some text value";
var textF
FromSession3
3 = sessionStorage.key;
Programming in HTML5 with JavaScript and CSS3 9-7
Note: You do not have to prefix these calls with the window object. You can call them
directly because window is the default calling context.
If you need to persist objects in session storage, serialize them as JSON strings by using the
JSON.stringify() function.
Note: In some browsers, the session storage API operates synchronously. However, Internet
Explorer implements this API asynchronously, meaning that there may be a delay between
writing a piece of data to session storage and that same data being available for reading. You can
force Internet Explorer to write data synchronously by using the begin() and commit() functions,
like this:
sessionStorage.begin();
sessionStorage.setItem("key","some text value");
sessionStorage.commit();
Objects in the session store are also accessible as an array of items with a long index. You can test the
length property to find out how many keys are in the sessionStorage object. You can retrieve the key for
each object by using the key() function. This information can be very useful for iterating over items, as
shown in the next code example, which creates a list of the keys in the sessionStorage object and
displays them in a <div> element :
sessionStorage.removeItem("key");
To clear a session store before the end of the session, call the clear() method:
sessionStorage.clear();
Remember that if you don't clear the data for a session, it will be cleared automatically when the user
closes the browser window. It is also important to understand that although data held in session storage
persists across a page refresh, it is only accessible to the page that stored the data. Consequently, session
storage may be of limited use in multi-page applications. This is where the Local Storage API may prove
more useful.
Additional Reading: For more information about the session storage API, visit
http://go.microsoft.com/fwlink/?LinkID=267733.
9-8 Adding Offline
O Support to Web
W Applications
Pe
ersisting D
Data Across Session
ns by Using Local Sttorage
Da
ata persisted in local storag
ge is available across differe
ent web pagess, although it is only availab
ble to web
pages running aas part of the website that stored the data; you cannoot used local sstorage to shaare data
be
etween pages originating frrom different websites.
Yo
ou access local storage by u
using the loca
alStorage property of the window
w object. You can dettect
wh
hether the bro
owser supportts local storag
ge by querying ence of this p
g for the prese property, as fo
ollows:
if( windo
ow.localStor
rage ){
...
}
localStor
rage.setItem
m("key","some text value
e");
var textD
Data = localStorage.getItem('key');
;
localStor
rage["key"] = "some text value";
var textD
Data = localStorage["key
y"];
localStor
rage.key = "
"some text value";
var textD
Data = localStorage.key;
Note: Simmilar to the sesssion storage API, the local storage API iimplemented by Internet
Explorer operate
es asynchrono ously.
Programming in HTML5 with JavaScript and CSS3 9-9
You can determine the number of items in local storage by using the length property, and iterate over
items and retrieve data by using the key() function, as shown in the following example:
localStorage.removeItem("key");
To remove all items from the store, call the clear() function:
localStorage.clear();
Objects stored in local storage do not have a specified size restriction. Instead, the store is free to grow to
an upper size limit decided by the user and configured in the browser settings. This makes it ideal to store
large amounts of data useful to the client-side application. As with the session storage API, you should
serialize objects as text by using the JSON.stringify() function before storing them.
Using local storage instead of relying on server round trips has a significant effect on the user experience.
Data found on the client can be displayed almost instantly, improving the responsiveness of the website.
Additional Reading: For more information about the local storage API, visit
http://go.microsoft.com/fwlink/?LinkID=267734.
9-10 Adding Offline Support to Web
W Applications
Handling Storage Ev
vents
function myStorageCa
allback( e ) {
alert
t("Key:" + e
e.key + " changed to " + e.newValue
e);
}
window.ad
ddEventListe
ener("storage", myStorag
geCallback, true);
• key: The na
ame of the value which hass changed.
• oldValue: T
The original vaalue before th
he change.
Intternet Explore
er also definess the storageccommit even
nt. Remember that in Internnet Explorer, the session
and local storagge APIs are asyynchronous. TThe storage event
e fires when data chang
ges, but the
stooragecommitt event occurs when the daata is actually written to dissk.
S
Storing Sttructured Data by U
Using the Indexed D
Database API
The Indexed D
T Database API, or IndexedDB, provides an n efficient mechanism for storing, retrievving, and
s
searching ata held locallyy on the devicce running the browser. Yo
for structured da ou access IndeexedDB by
u
using the indeexedDB prop perty of the w
window objectt.
You store data in a named database; you
Y u connect to a database byy using the op pen() function n. If the
d
database does not exist, it w
will be created. The Indexe edDB API is asynchronous, and a you use tthe
o
onsuccess evvent to capture the value re eturned by funnctions such aas open(). If a function failss, you can
d
determine thee reason for thhe failure by hhandling the onerror
o event. The following example shows how to
o
open a databaase and obtain a reference that you can use for storin ng and retrievving data. The db variable
h
holds a refereence to the daatabase, if it is opened succcessfully:
A database ho olds one or mmore object sto ores, which arre analogous to
t tables in a relational dattabase. You
d
define an obje ect store by using the createObjectStorre() function; you specify an object to ad dd to the
s
store together with the nam me of the keyy property that the IndexedDB API can use to retrieve the object.
T following example crea
The ates an objectt store for holding the detaails of confere
ence attendees. The object
s
store e—Rachel Valdez. The id property is the key to the
is initialiized with the details of the first attendee
o
object store:
var att
tendee = {
id: "1",
nam
me: "Rachel Valdez",
pas
ssword: "Pa$$w0rd"
};
var att
tendeeStore = db.createO
ObjectStore(
("attendees", { keyPath: "id" });
9-12 Adding Offline Support to Web Applications
Additional Reading: You should only create a new object store in the context of a
VERSION_CHANGE transaction. At the time of writing, the IndexedDB API specification is
currently fluid in this area. Some vendors initialize a VERSION_CHANGE transaction by using the
setVersion() function of a database, while other vendors start a VERSION_CHANGE transaction
implicitly if you specify the version number as a second parameter for the open() function of the
indexedDB object.
For more information, see the latest version of the IndexedDB specification at
http://go.microsoft.com/fwlink/?LinkID=267736.
You can use the add() function to store additional records in an object store. The next example adds the
details for Eric Gruber to the store. Notice that the add() function is asynchronous:
var newAttendee = {
id: "2",
name: "Eric Gruber",
password: "Pa$$w0rd"
};
var addRequest = attendeeStore.add(newAttendee);
addRequest.onsuccess = function(event) {
// Attendee was successfully added
}
addRequest.onerror = function(event) {
// Handle failure
};
If a record with the same key value as the new item already exists, the add() function fails and raises the
error event.
To modify an existing record, use the put() function, as follows:
var updatedAttendee = {
id: "2", // Id of existing attendee
name: "Eric Gruber",
password: "P@ssw0rd" // Change the password
};
var addRequest = attendeeStore.put(updatedAttendee);
addRequest.onsuccess = function(event) {
// Attendee was successfully updated
}
addRequest.onerror = function(event) {
// Handle failure
};
You can use the delete() function to remove an object from the object store. Specify the key of the object
as the parameter. If there is no matching object, the error event is raised. You should perform this
operation in the context of a transaction, to ensure that the operation can rollback successfully if an error
occurs:
To find data in the object store, you can use the get() function and specify the key of the object to
retrieve. Again, if there is no matching object, the error event occurs:
Programming in HTML5 with JavaScript and CSS3 9-13
var attendee;
var getRequest = tx.attendeeStore.get("2"); // Retrieve the details for Eric Gruber
getRequest.onsuccess = function(event) {
// Attendee details are available in event.target.result
attendee = event.target.result;
}
getRequest.onerror = function() {
// Handle failure
};
The IndexedDB API defines many more features. For example, you can use a cursor to fetch multiple
records from an object store, and you can define indexes to speed up queries that retrieve objects by
using specified properties.
Note: To use the IndexedDB API, Internet Explorer, must be configured to allow website
caches and databases. This option is available on the Settings page of the Internet Options
dialog in Internet Explorer; click the Caches and databases tab, and then select Allow website
caches and databases.
Additional Reading: For more information about using the IndexedDB API, visit
http://go.microsoft.com/fwlink/?LinkID=267737.
9-14 Adding Offline Support to Web
W Applications
Lesson 2
Addin
ng Offline Sup
pport by
y Using
g the Ap
pplicatiion Cacche
In this lesson, yo
ou will learn h
how to configure and use the HTML5 application cach
he in a website.
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
C
Configuri ng the Ap
pplication Cache
LLarge parts off web applicattions are simp ply file-based resources succh as HTML paages, CSS filess, JavaScript
f
files, and imag
ges. There is little point in d
downloading such static files over and o
over, and yet tthis is what a
t
typical browse
er session doees.
The applicatio
T on cache is a cclient-side sto
orage mechan nism that enabbles the developer to expliccitly declare
w
which static files should be cached by th he browser. Yoou can use thiis mechanism to create web bsites that
r just as we
run ell offline as th
hey do online,, making it ide
eal for develo
oping robust mobile
m applicaations that
h
have to run wwith intermitte ent network coonnections.
To add a man
T nifest file to ann application, create a new text file and sstore it in the root folder o
of the web
a
application. In
n this file, list all
a the static resources
r thatt should be do
ownloaded an nd cached. This list will
m
most likely incclude any graphics and imaages in the ap pplication, anyy HTML pagess that do not have URL
d
data depende encies, CSS file es and JavaScript files, and so on. An exaample manifesst file looks likke this:
CACHE MANIFEST
M
CACHE:
index.h
html
verific
cation.js
site.cs
ss
graphic
cs/logo.jpg
NETWORK
K:
login
# alter
rnatives paths
FALLBAC
CK:
ajax/ac
ccount/ noCode.htm
The cache manifest file starts with the line CACHE MANIFEST; if this line is missing, the file may not be
recognized as a manifest file. The file can contain the following sections:
• CACHE: Resources listed in this section are downloaded once, when the web page is initially loaded
into the user's browser. Thereafter, the cached version of these resources will be used and they will
not be updated from the server.
• NETWORK: Resources listed in this section will always be downloaded if the network is available.
They are not cached.
• FALLBACK: Resources listed in this section are not cached, but you provide an alternative URL for
them should the server become unavailable. In the example shown, all URLs prefixed with the
ajax/account/ path will be replaced with the noCode.htm file if they cannot be retrieved. The
alternative resources, such as the noCode.htm file in the example, are cached.
Note: Be sure to add the colon after the CACHE, NETWORK, and FALLBACK keywords,
otherwise they might not be recognized. If you do not specify any sections, then CACHE is
assumed.
You can add comments to the manifest file by creating a new line starting with the pound symbol, #.
To use the application cache, each web page must reference the manifest file that lists the resources to
cache. A website can contain multiple manifest files, and different web pages can reference different
manifest files. You specify the name of the manifest file to use in a web page by adding the manifest
attribute to the <html> element.
<html manifest="appcache.manifest">
Note: As with the IndexedDB API, to use an application cache, Internet Explorer, must be
configured to allow website caches and databases. This option is available on the Settings page
of the Internet Options dialog in Internet Explorer; click the Caches and databases tab, and
then select Allow website caches and databases.
Programming in HTTML5 with JavaScrippt and CSS3 9-17
7
M
Monitorin
ng with th
he Applicaation Cach
he
• checking
g: This event fiires when the browser exam
mines the app
plication cache
e for updates.
• cached: T
This event fire
es when the ap
pplication cacche is ready an
nd available for use.
applica
ationCache.addEventListe
ener( "error
r", function() {
ale
ert( "Error while downlo
oading resou
urces to the application
n cache");
}, true
e );
Note: Ju
ust as with the
e local storage and session storage obje
ects, you do no
ot have to
rreference the applicationC Cache propertty from the wwindow object, because thaat is the defau
ult
c
context.
9-18 Adding Offline Support to Web Applications
The application cache also implements a numeric status property that can be tested independently of
the event model. This property can have one of the following values:
4 UPDATEREADY The cache has been updated with new resources, and all
resources have been downloaded. The updateready
event has been fired.
Additional Reading: For more information about using the Application Cache API to
monitor the application cache, visit http://go.microsoft.com/fwlink/?LinkID=267738.
Programming in HTTML5 with JavaScrippt and CSS3 9-19
9
T
Triggering
g Resourcce Updates by Using
g the Man
nifest
To force an up
T on of an existing resource, you must make a significan
pdate to get tthe new versio nt change to
pdating the last modified date is not eno
t manifest ffile. Simply up
the ough to triggeer a complete refresh on
t browser. T
the The best way to force an up dd a commentts field in the manifest with
pdate is to ad h a version
n
number, for e
example:
#versio
on=1.2.3
#versio
on=1.2.4
applica
ationCache.update();
...
if (app
plicationCache.status ==
= 4 ) {
app
plicationCache.swapCache
e();
}
9-20 Adding Offline Support to Web
W Applications
Te
esting for Network Connectivity
Sometimes it makes sense to temporarily h hide or disable functionalitty in a web ap pplication if no o network
connection is avvailable. For example, if a wweb page expe ects a user to enter and sub bmit data to a server by
usiing a form, thhen this featurre will not work unless an aactive link to the server is avvailable. In sittuations
succh as this it do
oes not make e sense to cachhe the web paage.
Yo
ou can detect the network cconnectivity in n an applicatio
on by using the onLine pro operty of the navigator
ob perty that is trrue if a network connection
bject. This is a Boolean prop n is available, false otherwisse. The
naavigator objecct also provides two eventss called online e and offline
e. These events fire when thhe network
staate changes.
The following co
ode example shows how to o detect the nnetwork statuss of a page whhen it loads. T
The onload
eve
ent handler examines the o onLine prope
erty of the nav
vigator objecct and displayss the status in
n the
sta
atusDiv div on the page. The online andd offline even e the displayed status if
nt handlers firre and update
the
e network connnectivity chaanges.
var s = d
document.get
tElementById("statusDiv"
");
function(
() onlineSta
atus() {
s.inn
nerHTML = "O
Online.";
}
function(
() offlineSt
tatus() {
s.inn
nerHTML = "O
Offline.";
}
onload = function() {
if( n
navigator.on
nLine ) {
o
onlineStatus
s();
} els
se {
offlineSt
tatus();
}
windo
ow.addEventL
Listener("online", onlin
neStatus, tr
rue);
windo
ow.addEventL
Listener("offline", offl
lineStatus, true);
}
Programming in HTTML5 with JavaScrippt and CSS3 9-21
1
Lab: Adding
g Offlin
ne Supp
port to Web Applicat
A tions
S
Scenario
The conferencce organizers are concerne
T ed that the vennue has poor Wi-Fi coverag
ge in some locations,
m
meaning that attendees miight not alwayys be able to access the conference web
bsite on their ttablets and
l
laptops. The SSchedule page
e is especially important beecause attendees need to know
k when seessions are
r
running.
O
Objectives
A
After y will be able to:
completting this lab, you
• Use the A
Application Caache API to make
m es available offline.
web page
• Use the LLocal Storage API to persist user data loccally between browser sessiions.
E
Estimated Tim
me: 60 minutes
• Password
d: Pa$$w0rd
9-22 Adding Offline Support to Web Applications
First, you will complete the creation of an application manifest file, which lists all of the files that should be
cached for offline access. Next, you will reference the manifest file from the Home, About, Schedule, and
Location pages. Then, you will write JavaScript code that adapts the page navigation, hiding links to
pages that are not available offline. Finally, you will run the application and view the Schedule page. You
will stop the web server and then reload the Schedule page to verify that it works offline.
4. Start Visual Studio and open the ContosoConf.sln solution from the E:\Labfiles\Starter\Exercise 1
folder.
5. Open the appcache.manifest file. This file contains a partial application manifest that lists the
resources a web browser must cache for offline access.
6. Insert URLs to cache the Home, About, Schedule, and Location pages.
7. Add the manifest="/appcache.manifest" attribute to the <html> element of the Home, About,
Schedule, and Location pages. These are the pages that will operate offline by using the application
cache.
2. Add JavaScript code to detect if the web browser is currently offline, and call the
hideLinksThatRequireOnline function.
3. Handle the ononline and onoffline events of the document body; call the
hideLinksThatRequireOnline and showLinks functions as appropriate.
4. Add an event listener to the applicationCache error event, which calls the
hideLinksThatRequireOnline function.
FIGURE 9.1: THE IIS EXPRESS ICON IN THE WINDOWS NOTIFICATION AREA
3. In Internet Explorer, view the Schedule page. Verify that the page loads and displays the schedule
information. Also verify that, after a brief delay, the Register link in the navigation bar is removed.
This occurs because the Register page is not cached (it is not included in the appcache.manifest
file), and registration requires an active connection to the web site.
4. View the About page and verify that this page displays correctly, and that the Register link
disappears from the navigation bar.
5. Close Internet Explorer.
Results: After completing this exercise, you will have modified the web application and made the Home,
About, Schedule, and Location pages available offline.
9-24 Adding Offline Support to Web Applications
Note: The Local Storage API is very simple. It can only save and load string key-value pairs.
Persisting more complex data requires serialization. In this exercise, you will use a wrapper
around the Local Storage API that provides a more functional interface.
4. Use the local storage wrapper to save and load data in the Schedule page
3. Close IIS Express by using the icon in the Windows notification area.
4. On the Schedule page, click some of the stars, and then refresh the page.
5. Notice that information about which sessions are starred is not saved when the application is running
offline (the yellow stars turn white again).
6. Close Internet Explorer.
Note: The Schedule page will use the addStar, removeStar, isStarred, and initialize
functions defined in this file. These functions in turn call the save and load methods that you will
implement in this task.
• The IDs of the starred sessions to be saved are held in the array this.sessions.
Programming in HTML5 with JavaScript and CSS3 9-25
• Convert the array to a string by using the JSON.stringify function, and save this string to local
storage with the key stars.
X Task 4: Use the local storage wrapper to save and load data in the Schedule page
1. In the scripts\pages folder, open the schedule.js page.
2. In the initialize method, find the following comment:
• Detect whether the session identified by this.id is starred (use the isStarred method of the
localStarStorage object).
• If the session is starred, tag the element with the starred CSS class so that it is rendered correctly (use
the statement this.element.classList.add(this.starredClass);).
5. After this comment, add JavaScript code to remove the star from the session identified by this.id. Use
the removeStar method of the localStarStorage object.
6. In the setStar method, find the following comment:
7. After this comment, add JavaScript code to add a star to the session identified by this.id. Use the
addStar method of the localStarStorage object.
CACHE MANIFEST
# version 2
...
Note: The JavaScript files are listed in appcache.manifest, so will have been cached by the
web browser. Making a change to the appcache.manifest file forces the browser to download
the updated scripts.
3. In Internet Explorer, refresh the page to ensure the updated scripts are used.
4. Close IIS Express by using the icon in the Windows notification area.
9-26 Adding Offline Support to Web Applications
5. On the Schedule page, click some of the stars, and then refresh the page.
Results: After completing this exercise, you will have updated the Schedule page to locally record starred
sessions.
Programming in HTTML5 with JavaScrippt and CSS3 9-27
7
Module Rev
view an
nd Take
eaways
M
Module Rev
view
IIn this module e, you have se
een several techniques thatt you can use to store data locally on the e device that
i running the
is e browser. Theese techniquees include sesssion storage fo
or storing sesssion data thatt is
a
automatically removed when the user's browsing sesssion complete es; local storag
ge, which provvides for
m
more persistent data on the user's device; and the Inddexed Database API, which enables the b browser to
s
store and retrrieve data in a more structu
ured manner.
V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.
Statement Answer
Module 10
Implementing an Adaptive User Interface
Contents:
Module Overview 10-2
Modu
ule Ove
erview
Ob
bjectives
Aftter completing this module
e, you will be able to:
Lesson 1
Supp
porting Multip
ple Form
m Facto
ors
The number o
T of different de
evices and forrm factors now w capable of vviewing a web bsite has incre
eased greatly
o
over the past few years. But is it a good idea to create e a 'one size fits all' website
e? What are th he
a
alternatives nd what are the differencess to look for in a website taargeted at traditional deskttop use,
an
v
versus mobilee or touch use ers? In this lessson, you will cconsider some e of the issuess involved in ssupporting
m
multiple form
m factors in a website.
w
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain w
why a website should be able to respond appropriatelyy to users view by using
wing the site b
different devices.
• Describe the changes tthat are typica website to be viewed by using different
ally necessaryy to enable a w
devices.
10-4 Implementing an Adaptive User Interface
W Design
Why n an Adap
ptive Userr Interface
e?
It iis also importaant to review the statistics of the users vvisiting the we
ebsite, togethe
er with their b
behavior
and their device es, so that youu can adapt th he website design and struccture to best meet their ne eeds;
patterns of use may change o over time as new
n devices become more mainstream.
sets of layout for the same content, and optimizing this layout for each set of pages. The benefit of this
approach is that users with smartphones will get a faster, more usable site than if the developer follows
the 'one size fits all' strategy. Ultimately, the question of whether to follow an adaptive approach or to
implement mobile versions of content should be decided based on user statistics and logs, rather than an
initial guess before the website has been launched.
10-6 Implementing an Adaptive User Interface
Co
onsideratiions for Su
upporting
g Different Types off Device
Sccreen Resolution
The most obvious difference between a sm martphone and a desktop m monitor is the
e screen resolu
ution, and
theerefore the pootential size o
of the browserr window or vviewport. As part of a respo onsive design, your site
mu ust be usable on any screen n, whether it iis 480, 1280, o
or 2560 pixelss wide. Your website
w may addapt
diffferent types o
of content by using the straategies in the following listt:
• Text. Chang ge the font sizze for lower vviewport sizes so that text remains
r readaable. Decrease
e the font
size as the vviewport size increases. You u can also try to adapt the way in which the browser d deals with
line breaks by switching on hyphenatiion, and add h hints by usingg the <wbr />> element, as well as CSS
hyphenatio on and wrappiing propertiess.
• Images. Shrink and grow w image size tto a minimum m/maximum widthw by settin
ng width and h height
properties rrelative to the
e screen or vie
ewport size. Alternatively, yyou can create ed versions
e different-size
of your imaages and displlay the appropriate image in the browse er window when the size off the
window fallls within a cerrtain range.
ones. You can also use 'fluid columns' that change their width as the viewport width is changed, but
above and below a certain point, extra-narrow or extra-wide columns look unappealing (the optimum
column width is 480 - 600px). In these situations, you should change the number of columns.
Note: Module 6, "Styling HTML5 by Using CSS3", described how to change the layout of a
web page as the width increases or decreases.
• Navigation. If necessary, consider changing the main navigation menu from a list to a drop-down
menu. This modification saves space and increases functionality.
When you are testing a website to see how it responds to different screen sizes, you can use the Internet
Explorer F12 Developer Tools to accurately resize your browser window to a given window size. On the
Tools menu, click Resize to set a custom size, or pick one of the preset sizes.
Display Density
The resolution of a screen has varied widely for a while, but only recently has the density of a screen
(measured in dots per inch, or dpi) started to vary enough to make it worthwhile for browsers to detect
and react to it. Increased screen density enables applications to present data with much greater clarity by
using common screen resolutions. However, a larger screen density can cause the operating system to
scale up all elements on a page, which can result in blurry images. To counter this problem, you can adopt
the following strategies for text and image data:
• Text. Increase the font size for higher-density displays.
Note: You can also use media queries to detect the density of the display device. This
approach is described in the next lesson.
• Images. Use a graphics editor to create copies of your graphics and images at a higher dpi, or, failing
that, a bigger size. Alternatively, you can recreate the images as Scalable Vector Graphics (SVG), which
will scale up perfectly.
Note: Module 11, "Creating Advanced Graphics", describes how to use SVG to create
scalable graphics.
Input Method
When it comes to designing the user experience of a website for a touch-based device, remember that a
finger will never be as accurate as a mouse pointer. This has an impact on the features that a user uses to
interact with your application:
• Buttons and Links: Make buttons and links larger than normal so users can easily identify them and
tap them with a finger. Again, consider changing list-based menus into one larger drop-down menu
to enhance usability.
• Hovering: Hover states do not exist on a touch-based device. There is no way to simulate a mouse
pointer over a link, so don't use the hover pseudo-class.
• Screen Orientation: Touch-based devices are nearly all handheld and can usually change their
orientation depending on how the user holds them. Make sure your design works in both landscape
and portrait mode. Switching between the two is effectively a change in resolution, so treat it as such.
10-8 Implementing an Adaptive User Interface
Additional Reading: Internet Explorer 10 includes a new events model targeted at touch-
based devices. For more information, read http://go.microsoft.com/fwlink/?LinkID=267740.
Browser Capabilities
Different browsers often have very different levels of functionality. For example, Internet Explorer 10
implements many (but not all) of the features specified by HTML5 and CSS3, while browsers from other
vendors implement a frequent cycle of releases to react to standards changes. You also need to consider
the mobile versions of browsers (including mobile versions of Internet Explorer) that have their own levels
of compliance.
The website at http://go.microsoft.com/fwlink/?LinkID=267741 provides information on which browsers
support which features of CSS3 and HTML5.
Printers
Users may want to print copies of selected parts of a web page, such as a map or directions to an
organization's office, for later use offline. The form factor to consider here is A4 paper, where navigation,
site logos, and design are irrelevant. The only thing that matters is the presentation of the content. You
can create a print style sheet to apply the following changes:
• Non-content: Remove the page header, footer, navigation menus, background colors, CSS graphics,
transforms, and animations.
• Text: Set the size of your fonts to values in points as you would a Microsoft Word document, their
color to dark grey, and remove any text-shadow.
• Columns: Layout your content in one column, unless it includes an index or glossary, in which case
two columns is acceptable.
These techniques are described in more detail in the next lesson.
Screen Readers
Using the web is an entirely different experience for the visually impaired. Reading web content and
navigation are both achieved aurally. When using aural properties, the canvas consists of a three-
dimensional physical space (sound surrounds) and a temporal space (one may specify sounds before,
during, and after other sounds). The CSS properties also allow you to vary the quality of synthesized
speech (voice type, frequency, inflection, and so on.), the direction it comes from, and modify pauses,
cues, and volume.
Programming in HTTML5 with JavaScrippt and CSS3 10-9
9
Lesson 2
Creatting an
n Adapttive Use
er Interrface
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
CS
SS Media Types
• projection:: Projectors.
• tty: Teletyp
pes.
• tv: Televisio
ons and otherr low-resolutio
on devices witth limited abillity to scroll.
<link rel
l="styleshee
et" type="tex
xt/css" href
f="core.css"
" media="all" />
<link rel
l="styleshee
et" type="tex
xt/css" href
f="print.css
s" media="print" />
The @media CSSS rule performs a similar task to the me edia attribute. It enables yo
ou to identify a set of
styyling rules for a media type
e within an exiisting style sheet, rather tha
an by creating
g a separate sstyle sheet
spe ecific to each media type. Y
You use the @
@media rule like this:
@media pr
rint {
header
r, footer { display: none; }
...
}
In this example, the header aand footer CSSS rules applyy only to printed media.
Programming in HTML5 with JavaScript and CSS3 10-11
You can combine multiple media types together if you need to apply the same styling rules to them. The
following example shows how to style the header and footer for printers and projectors:
Note: In 2011, the CSS 2.1 specification revised the list of media types for the @media rule,
deprecating aural and adding embossed and speech instead.
Additional Reading: For more information about media types, visit
http://go.microsoft.com/fwlink/?LinkID=267742.
10-12 Implem
menting an Adaptivve User Interface
Detecting Device
D Capabilities by Using Media Qu
ueries
Me edia queries in
n HTML5 and CSS3 enhancce the concep pt of media types; they enabble developerrs to inspect
thee physical cha
aracteristics off a device, including device
e height and width,
w orientattion, and reso
olution.
Altthough mediaa queries cann not tell you thhe exact type of device, you
u can use themm to infer thiss
infformation. Forr example, at the time of w uld reasonably assume that a device with a screen
writing you cou
wid dth of 480px or less is a mo
obile phone, aand use this kknowledge to style content accordingly.
A media
m query has
h two parts:
• A media typ
pe, such as screen, print, sp
peech, and so on.
<link rel
l="styleshee
et" type="tex
xt/css" href
f="mobile.cs
ss"
media="
"screen and (max-device-width: 480p
px)" />
@media sc
creen and (m
max-device-width: 480px)
) {
article
e {
colum
mn-count: 1;
}
...
}
Yo
ou can include
e multiple que
eries by conca
atenating them
m with and, or, and not. Fo
or example:
@media sc
creen and (m
max-device-width: 480px)
) and (resolution:300dpi) {
...
}
Yo
ou can test forr 13 device characteristics in
n a media que
ery. The follow
wing list summ
marizes these
characteristics.
• width, heig
ght: The width
h and height of the viewpo
ort (usually the
e browser win
ndow).
• device-wid
dth, device-height: The width and heigh
ht of the activve device screen (or paper, if printing).
Programming in HTML5 with JavaScript and CSS3 10-13
• resolution: The pixel density (in dpi or as a ratio) of the target device.
• aspect-ratio: The width to height ratio of the viewport.
• color-index: The total number of colors the target device screen can show.
• scan: The scanning method of a TV. Possible values are progressive and interlace.
All of these characteristics except scan and grid also allow you to query for minimum and maximum
values as well. For example, you can specify min-width, max-width, min-resolution, max-resolution,
and so on.
By using media queries, you can implement a responsive design for your website that takes into account
the size of the viewport displaying the web pages.
When using media queries, it is good practice to decide what all of your styles will be for either a large or
a small viewport size, and then use media queries at the end of a page to override the primary styles for
gradually decreasing or increasing sizes. This code example takes a mobile-first approach, and then
overrides fonts and columns for larger viewports.
Note: Note that some browsers support vendor-prefixed properties. These properties are
ignored by browsers that do not recognize them.
10-14 Implementing an Adaptive User Interface
Detecting
D g the Versiion of Inte
ernet Explorer by Using
U Conditional
C
Comment ts
<!--[if
f IE 10]>
<p>Welc
come to Internet Explore
er 10.</p>
<![endif]-->
You can use the ! operator to reverse the sense of a ccondition. You
Y u can also use the IE operan
nd in isolation
n
t determine whether the user
to u is running another ven ndor’s browseer, like this:
<!--[if
f !(IE)]>
<p>You are not using Internet Explorer.</
/p>
<![endif]-->
<!--[if
f lt IE 10]>
<p>Plea
ase upgrade to Internet Explorer 10
0.</p>
<![endif]-->
10-16 Implementing an Adaptive User Interface
The next example shows how to use conditional comments to load an appropriate style sheet for the
version of Internet Explorer that runs on the user’s operating system:
<html>
<head>
<link href="styles.css" rel="stylesheet" />
<!--[if IE 8]> <link href="ie8.css" rel="stylesheet" /><![endif]-->
<!--[if lt IE 8]> <link href="ie7.css" rel="stylesheet" /><![endif]-->
<!--[if gte IE 9]> <link href="ie9.css" rel="stylesheet" /><![endif]-->
<!--[if IEMobile7]> <link href="winPhone7.css" rel="stylesheet" /><![endif]-->
<!--[if !(IE)]> <link href="otherBrowsers.css" rel="stylesheet" /> <![endif]-->
...
</head>
...
</html>
In this example,
• The page loads a style sheet called styles.css.
• If the browser is Internet Explorer for Windows Phone 7, it also loads winPhone7.css.
If you follow this approach, you can prefix styles with the version of Internet Explorer to which the style
applies. For example, the following code sets box model properties for an article element, and then adds
a correction for Internet Explorer 6:
article {
width: 200px;
margin: 10px;
border: 5px solid red;
padding: 10px;
}
ie6 article {
width: 250px;
}
You can also use conditional comments to include scripts in a web page, as follows:
<!--[if IE]>
<script src="http://contoso.com/scripts/iescript.js"></script>
<![endif]-->
D
Defining S
Style Shee
ets for Printing
<link rel="stylesh
r eet" type="t
text/css" hr
ref="print.css" media="p
print" />
@media print {
.. pr
rint styling rules go heere ..
}
article
e, p, li {
font-
-size : 14pt\1.5; color: #222; text
t-shadow : none;
}
10-18 Implementing an Adaptive User Interface
• Expand any links and abbreviations on the page so that the URL of the link or the expanded text of
the abbreviation is printed to the right of the text.
a:after {
content: " (" attr(href) ")";
}
abbr:after {
content: " (" attr(title) ")";
}
• Lay out the content in one column, unless it includes an index or glossary, in which case two columns
is acceptable.
article {
column-count : 1;
}
#glossary {
column-count : 2;
}
• Define the target size of the printed page, the margins around facing pages, and the minimum
number of lines in a paragraph printed at the top (widows) and the bottom (orphans) of the page.
You can use the @page rule to achieve this.
@page {
size: A4;
orphans: 3;
widows: 3;
}
@page :left {
margin-left: 3cm;
margin-right: 4cm;
}
@page :right {
margin-left: 4cm;
margin-right: 3cm;
}
Additional Reading: For more information about using CSS to optimize pages for printing,
visit http://go.microsoft.com/fwlink/?LinkID=267745.
P
Programming in HTM
ML5 with JavaScript and CSS3 10-19
9
Lab: Implem
menting
g an Ad
daptive User In
nterface
e
S
Scenario
Most conferen
M nce attendeess are expectedd to use a lapttop to view th
he live version
n of the Conto oso
C
Conference w
website, but soome may wish h to print a hard copy of some of the info ormation. Oth her attendees
m
might use smartphones or other handhe eld devices to view the web bsite. The diffe
erent requiremments and
f
form factors o
of a printer orr a handheld d
device compared to a lapto op make it neccessary for the user
i
interface of th
he web application to detecct device capaabilities and aadapt itself acccordingly. Forr example,
s
some websitee elements, such as the header, are not nnecessary for pprinting, whilee the smaller screens
s of
s
smartphones are not ideal for viewing fu
ull-sized webssites.
O
Objectives
A
After completting this lab, you
y will be able to:
• Use CSS m
media queriess to enable a web
w page to adapt
a to diffe
erent device fo
orm factors.
E
Estimated Tim
me: 60 minutes
• User Nam
me: Student
• Password
d: Pa$$w0rd
10-20 Implementing an Adaptive User Interface
In the style sheet, you will add rules to override the layout of the website, removing the header and
footer, and reformatting the About page to display the information in a single wide column. To test the
application, you will view the About page and verify that the print preview displays a correctly formatted
version of the page.
2. Start the 20480A-SEA-DEV11-10 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 1
folder.
The Print Preview version of the About page looks like this:
2. In the print.css style sheet, delete the existing contents and add a CSS rule to hide the nav, header,
and footer elements.
3. Add a CSS rule for the .container class, which overrides the CSS from site.css. When printing,
container elements should have no maximum width or padding.
4. The about.css style sheet in the styles/pages folder contains a CSS rule to display the page text in
columns. In print.css, add a CSS rule that removes the columns, so that the text displays as a single
block.
10-22 Implem
menting an Adaptivve User Interface
X Task 3: Lin
nk the Printt Style Shee
et to the Ab
bout Page
1. Add a link tto print.css in
n the About page.
p Set the m
media attribu
ute of the linkk so that the sttyle sheet is
used only w
when printing.
X Task 4: Te
est the Appllication
1. Run the app
plication and view the Abo
out page.
3. In Internet Explorer, open the Print Prreview windo ow and verify that the preview does not display the
navigation, header, or fo
ooter, and thatt the text has no columns.
Results: After completing this exercise, you will have added a style sheet that implements a print-friendly
format for web pages.
10-24 Implementing an Adaptive User Interface
First, you will view the application running in a small window to simulate a small device, such as a
smartphone. Then you will use CSS media queries to define rules that change the website layout to better
suit small devices.
Finally, you will run the application again and verify that the website layout adapts to large and small
screen sizes.
3. Resize Internet Explorer to 480 × 800, approximating the form factor of a Windows Phone 7 device.
Note: Use the F12 Developer Tools to change the size of the device viewing the website.
The Resize command on the Tools menu enables you to change the size of the browser.
4. Notice that the website navigation bar does not fit on the screen and that the big Register link
overlaps the header text.
PProgramming in HTM
ML5 with JavaScript and CSS3 10-25
5
The Hom
me page should look like this:
FIGUR
RE 10.3: THE H
HOME PAGE
5
5. Close Inte
ernet Explorerr.
10-26 Implementing an Adaptive User Interface
2. Add a CSS media query that targets screens that are less than or equal to 480 pixels in width.
3. In the media query, add a rule for nav.page-nav .container that contains the following properties:
display: -ms-flexbox;
-ms-flex-wrap: wrap;
-ms-flex-pack: center;
4. Add another rule that hides the :before and :after pseudo elements of the .active navigation link.
5. Add another rule that sets a small margin around each navigation link. This rule should also set a
dotted border completely around the link, instead of just on the right.
1. The default layout of the website header is not suitable for screens less than 720 pixels wide. Add
another media query to mobile.css that targets screen widths up to 720 pixels.
2. Reduce the height of the header (set the height to auto), hide the large Register link in the header,
and reduce the font-size of the <h1> element in the header to 3rem.
2. Use the F12 Developer Tools to resize Internet Explorer to various sizes to test that the media queries
adapt the user interface correctly.
Results: After completing this exercise, you will have a website that adapts to different screen sizes.
P
Programming in HTM
ML5 with JavaScript and CSS3 10-27
7
Module Rev
view an
nd Take
eaways
M
Module Rev
view
IIn this module e you have lea
arned why it iis necessary too create webssites that can dynamically
d aadapt to
d
different devicces and browwsers. You have e seen the maain considerattions when taiiloring a page e to different
f
form factors aand browsers, and you have e learned—byy using mediaa types, media a queries, and conditional
c
comments—h how to detectt the form facttor and browsser in CSS and d HTML5. And d finally, you hhave learned
h
how to implem ment a basic sstyle sheet suitable for prin
nting content.
n: How can yo
Question ou detect whe
ether a user is running Interrnet Explorer to view your w
web
page?
11-1
Module 11
Creating Advanced Graphics
Contents:
Module Overview 11-2
Modu
ule Ove
erview
This module desscribes how to o create advanced graphicss in HTML5 byy using Scalab ble Vector Graaphics
(SV
VG) and the M Microsoft Canvvas applicatio
on programming interface ((API). You will learn how to
o use SVG-
related elementts such as <reect>, <ellipse e>, and <poly play graphical content on a web page.
yline> to disp
Yoou will also lea
arn how to enable the user to interact wiith SVG eleme
ents through tthe use of eveents such as
keyyboard events and mouse events.
The Canvas API is somewhat different than n SVG. The Caanvas API provvides a <canvvas> element and a set
of JavaScript fun
nctions that yyou can invoke
e to draw graphics onto thee canvas surfaace. You will le
earn how
to use the Canvvas API, and also find out w
when it is more
e appropriate to use Canvas or SVG.
Ob
bjectives
Aftter completing this module
e, you will be able to:
Lesson 1
Creatting Intteractiv
ve Grap
phics by
y Using
g SVG
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Create an
n <svg> elem
ment and embed simple gra
aphical elements inside it.
• Use SVG tto draw circle
es and ellipsess.
W
What is SVG
G?
SV
VG defines a se
et of elements that that rep present comm mon types of d drawing shapees. For examp
ple, there
are
e SVG-related
d elements named <rect>, <text>, <ellipse>, <poly ygon>, and <path>. SVG im mplements
tw
wo-dimensionaal vector grap phics that scale
es to the size of the user's browser
b window and the reesolution of
the
e screen on w
which it is runn
ning.
SV
VG uses a retaiined mode model. When yyou add SVG-rrelated eleme ents to an HTMML5 web page e, the
ele
ements are ke
ept in the DOM M tree for the
e web page, an
nd a user can interact with them in the ssame way
as they would w
with HTML ele ements such as <h1>, <div v>, and <buttton>. As a de eveloper, you can
erform the folllowing actions:
pe
• Handle events such as m mouse events aand keyboard events on SV VG-related ele
ements. For exxample, you
can use SVGG to create a complex
c grap
phical figure, aand then hand
dle mouse clicck events to e
enable the
user to inte
eract with speccific elementss within the fig
gure.
C
Creating S
SVG Graphics
T use SVG in
To n a web page, add an <svg> element an
nd specify an XML
X namespaace as followss:
<svg xm
mlns="http://www.w3.org/
/2000/svg">
...
</svg>
• x and y: T
The position o
of the shape within
w the <sv
vg> element, relative to the
e left hand sid
de and the
top of the
e <svg> elemment, respectivvely.
• fill and sttroke: The fill color and strroke color of tthe shape.
<svg xm
mlns="http://www.w3.org/
/2000/svg">
<rect
t x="50" y="50" width="1
100" height=="75" rx="20" ry="20" fi
ill="red"
stroke=
="blue" />
<rect
t x="75" y="75" width="1
100" height=="75" fill="yellow" stro
oke="blue" />
/
</svg>
11-6 Creating Advanced Graphics
You can define CSS styles for <svg> elements, and for the elements that are contained inside an SVG
element. The following example defines a style sheet rule for all <svg> elements. The rule specifies that
all <svg> elements have a dark blue border, a background color of light green, a width of 300 pixels, and
a height of 200 pixels:
<style type="text/css">
svg {
border: 2px solid darkblue;
background-color: lightgreen;
width: 300px;
height: 200px;
}
</style>
Programming in HTTML5 with JavaScrippt and CSS3 11-7
7
D
Drawing C
Circles and
d Ellipses
C
Circle
The <circle> element has cx and cy pro
T operties that sspecify the loccation of the ccenter point ffor the circle
i
inside the <sv
vg> element. <circle> also
o has an r attrribute that speecifies the rad
dius of the circcle.
<svg xm
mlns="http://www.w3.org/
/2000/svg">
<circle cx="120" cy="80" r
r="40" strokke="blue" fill="red" />
<circle cx="160" cy="120" r="60" strooke="blue" fill="yellow"" />
</svg>
E
Ellipse
The <ellipse>
T > element hass cx and cy prroperties that specify the lo ocation of the
e center point.. <ellipse>
a has rx an
also nd ry attribute
es that specifyy the radius off the ellipse in
n the X and Y directions. If rrx and ry are
t same, the ellipse will ap
the ppear as a circcle.
<svg xm
mlns="http://www.w3.org/
/2000/svg">
<ellipse cx="150" cy="60" rx="110" ryy="30" stroke="blue" fil
ll="red" />
<ellipse cx="150" cy="140"
" rx="110" ry="30"
r stroke="blue" fi
ill="yellow"
" />
</svg>
11-8 Creatingg Advanced Graphiccs
Drawing Co
omplex Sh
hapes
SV
VG defines <polyline>, <po
olygon>, and
d <path> elements that en
nable you to d
draw complexx shapes in
an <svg> element.
Po
olyline
The <polyline> > element creaates a line draawing comprising a series o of connected points. The po oints are
speecified by the
e points attrib
bute, which de efines a comm ma-separated series of X annd Y coordinattes. A
po
olyline does no ot connect thee last point baack to the firsst point. The <
<polyline> ellement has vaarious
atttributes such aas stroke and fill, which ena
able you to co onfigure the aappearance off the polyline..
<svg xmln
ns="http://w
www.w3.org/20
000/svg">
<poly
yline points
s="105 100, 120 100, 125
5 90, 135 11
10, 145 90, 155 110, 165
5 90, 175
110, 180 100, 195 10
00" fill="none" stroke="
"blue" />
</svg>
Po
olygon
The <polygon> > element is similar
s to the <polyline> e
element, excep
pt that a polygon connectss the last
po
oint back to th
he first point tto form a closed shape.
<svg xmln
ns="http://w
www.w3.org/20
000/svg">
<poly
ygon points=
="110 70, 150
0 40, 190 70
0, 190 160, 150 130, 110
0 160" fill=
="yellow"
stroke="b
blue" />
</svg>
Pa
ath
The <path> eleement enabless you to draw w a complex sh hape as a serie
es of path seg
gments. The <
<path>
ele
ement has a d attribute tha
at defines the outline of the
e shape. The d attribute comprises a seriies of
dra
awing commaands as follow ws:
• M: Move to
o a new location, without drawing a line..
• Q: Draw a quadratic Bezier curve. A quadratic Bezier curve is a curve that joins two points, and has
one turning point along its journey.
• C: Draw a cubic Bezier curve. A cubic Bezier curve is a curve that joins two points, and has two turning
points along its journey.
• Z: Close the current path by connecting the last point back to the first point.
The following example creates a simple path that draws a solid red triangle with a blue outline. The M
command moves the current location to (150, 50). The first L command draws a line from the current
location to (250, 150). The next L command draws a line from the current location to (50, 150). The Z
command closes the path, by drawing a line back to the starting point of (150, 50):
<svg xmlns="http://www.w3.org/2000/svg">
<path d="M 150 50 L 250 150 L 50 150 Z" fill="red" stroke="blue" />
</svg>
Additional Reading: For more information about the <path> element, including details
on how to draw arcs and Bezier curves, see http://go.microsoft.com/fwlink/?LinkID=267746.
11-10 Creating Advanced Graphhics
Sp
pecifying Fill Styles and Strok
ke Styles
SV
VG-related elements have a series of attributes that en
nable you to specify
s how to
o fill an eleme
ent and how
to draw its outline. These attrributes include:
• stroke and fill: Specify the outline collor and the fill color of the shape, respecctively.
• stroke-opa acity and fill-opacity: Speccify the opacitty of the outline and the fillling of the sh
hape,
respectivelyy. The opacityy is a fractionaal value betwe
een 0.0 and 1.0. A value of 0
0.0 means com mpletely
transparentt, and a value of 1.0 means completely o opaque. The ddefault opacityy is 1.0.
• stroke-widdth: Specifies the
t width of tthe outline, either as an abssolute size or as a percenta
age of the
shape size.
• pecifies how to
fill-rule: Sp o determine what
w side of a path is inside
e the shape. T
The fill-rule atttribute is
important in complex ovverlapping shaapes, because it enables SV VG to determine which partts of the
shape to fill with the fill ccolor. There are two possibble values for fill-rule:
f nonzzero and evenodd.
<svg xmln
ns="http://w
www.w3.org/20
000/svg">
<rect
t x="10" y="
"10" width="50" height="
"50" fill="b
black"/>
</svg>
Programming in HTML5 with JavaScript and CSS3 11-11
The next example creates a rectangle with no interior and a light blue outline:
<svg xmlns="http://www.w3.org/2000/svg">
<rect x="70" y="10" width="50" height="50" fill="none" stroke="lightblue"/>
</svg>
The next example creates a rectangle with a yellow interior and a thick, semi-transparent purple outline:
<svg xmlns="http://www.w3.org/2000/svg">
<rect x="10" y="70" width="50" height="50"
fill="yellow"
stroke="purple"
stroke-width="5"
stroke-opacity="0.5" />
</svg>
The final example creates a rectangle with a semi-transparent yellow interior and a dashed purple outline:
<svg xmlns="http://www.w3.org/2000/svg">
<rect x="70" y="70" width="50" height="50"
fill="yellow"
fill-opacity="0.5"
stroke="purple"
stroke-width="2"
stroke-dasharray="2 2" />
</svg>
11-12 Creating Advanced Graphhics
SV
VG provides thhree elementss that enable yyou to specifyy gradients and patterns thaat you can use to fill a
shaape or draw aan outline:
• <linearGrad
dient>
• <radialGrad
dient>
• <pattern>
Th
he <linearG
Gradient> E
Element
The <linearGra adient> eleme
ent creates a linear gradiennt of colors that can be appplied to a shappe. The
<linearGradien nt> element h
has four attrib
butes to define
e the start andd end location
ns of the lineaar gradient
on
n the target sh
hape:
• x1 and y1: Specifies the start point of the linear graadient on the target shape..
• x2 and y2: Specifies the end point of tthe linear gradient on the ttarget shape.
ou can specify any number of color stopss in a linear grradient. Each color stop is sspecified as a <stop>
Yo
nd has two atttributes:
child element an
The following exxample showss how to defin ne a linear graadient. The lin
near gradient starts at the ttop left
corner of the target shape, be ecause the x11 and y1 value es are 0%. Thee linear gradie
ent ends at thhe top right
corner of the target shape, be ecause the x22 value is 100% % and the y2 value is 0%. T The linear graadient
the
erefore define t top of the target shape. There are three color stop
es a horizontaal line across the ps that are
ap
pplied along thhis line, creating a linear grradient that raanges from ye ellow to green
n, and then fro om green
to red:
<svg xmln
ns="http://w
www.w3.org/20
000/svg">
<line
earGradient x1="0%" y1="0%" x2="100
0%" y2="0%">
>
<
<stop offset
t="0.2" stop-color="yell
low" />
<
<stop offset
t="0.5" stop-color="gree
en" />
<
<stop offset
t="1.0" stop-color="red"
" />
Programming in HTML5 with JavaScript and CSS3 11-13
</linearGradient>
</svg>
<svg xmlns="http://www.w3.org/2000/svg">
<radialGradient id="gradient2" fx="0.3" fy="0.3">
<stop offset="0.1" stop-color="yellow" />
<stop offset="0.7" stop-color="red" />
</radialGradient>
</svg>
The following example shows how to define a pattern based on an image file named "wales.png".
<svg xmlns="http://www.w3.org/2000/svg">
<pattern patternUnits="userSpaceOnUse" width="100" height="100">
<image xlink:href="wales.png" x="0" y="0" width="100" height="100" />
</pattern>
</svg>
Note: The patternUnits attribute controls how the image in a pattern is displayed. The
value userSpaceOnUse causes the image to be repeatedly tiled without any spacing.
The following example defines three reusable gradients and patterns, and gives each one a unique id. The
example then creates several shapes. The shapes make use of the gradients and patterns by referencing
their id values:
<svg xmlns="http://www.w3.org/2000/svg">
<!-- Define some gradients and patterns, for use later -->
<defs>
<linearGradient id="gradient1" ... />
<radialGradient id="gradient2" ... />
<pattern id="wales" ... />
</defs>
11-14 Creating Advanced Graphics
<!-- Draw shapes that make use of the gradients and patterns -->
<polygon points="50,50 250,50 150,200" fill="url(#gradient1)" />
<ellipse cx="150" cy="50" rx="100" ry="20" fill="url(#wales)" />
<circle cx="150" cy="250" r="50" fill="url(#gradient2)" />
</svg>
P
Programming in HTM
ML5 with JavaScript and CSS3 11-15
5
D
Drawing G
Graphical Text
S
SVG provides ways to custo
omize the app
pearance of te
ext:
• Text style
e
• Text deco
orations
• Text path
hs
• Text span
n
T
Text Style
The <text> e
T element has a range of attriibutes that ennable you to specify the texxt style. For exxample, you
c set the filll, stroke, and
can w the filling and outline for the text. You
d stroke-widtth attributes tto define how
c also set th
can he font-size, font-family, and font-weight attribute es to specify thhe font for the text. The
f
following example shows h how to use the
ese attributes::
<svg xm
mlns="http://www.w3.org/
/2000/svg">
<te
ext x="20" y="50"
fill="yellow" str
roke="purplee" stroke-width="2"
font-size="36" fo
ont-family=""verdana" font-weight="b
bold">
Styled text
</t
text>
</svg>
T
Text Decorrations
The <text> e
T element has a text-decorattion attribute
e that takes a space-separat
s ted list of textt decorations.
T following text decoratiions are suppo
The orted:
• underline
e
• overline
• line-throu
ugh
11-16 Creating Advanced Graphics
• blink
The following example shows how to set text decorations on <text> elements. The <text> elements are
grouped inside a <g> element in this example. The <g> element defines a common set of styles that
apply to all <text> elements in the group:
Text Paths
A <text> element can contain a <textPath> child element that indicates a path to use as the baseline for
the text when it is displayed on the web page. For example, you can create a <textPath> that draws text
around the perimeter of another shape on the page.
The following example shows how to use <textPath>. In this example, a <path> element is created to
represent a wavy line. The <text> element has a <textPath> child element that links to the <path>
element by using an XLink expression:
Text Spans
A <textSpan> element can contain any number of <tspan> child elements that partition the text into a
series of discrete sections. Each section can be styled individually.
The following example shows how to partition a <text> element by using multiple <tspan> elements. The
<tspan> elements specify how to draw that particular part of text:
Trransformatiions
To
o transform an
n element, set the transform attribute to
o one of the ffollowing valu
ues:
• rotate(ang
gle, cx, cy): Ro
otates the shaape by the spe
ecified angle, about the spe
ecified (cx, cy)) center
point.
• dx, dy): Translates the shap
translate(d pe by the speccified distance
e in the X and Y directions.
• scale(sx, sy
y): Scales the shape by the specified fracction in the X and Y directio
ons.
• skewX(ang
gle): Skews the shape by th
he specified an
ngle in the X d
direction.
• skewY(ang
gle): Skews the
e shape by the specified an
ngle in the Y d
direction.
<svg xmln
ns="http://w
www.w3.org/20
000/svg" id=
="transforma
ations" >
<defs
s>
<
<pattern id=
="checkerPattern" width=
="80" height
t="80"
patternUn
nits="userSp
paceOnUse">
<rect fill="red" x=="0" y="0" width="40" " height="40" />
<rect fill="blue" x=
="40" y="0" width="40"" height="40" />
<rect fill="blue" x=
="0" y="40"" width="40"
" height="40" />
<rect fill="red" x=="40" y="40"
" width="40"
" height="40" />
<
</pattern>
</def
fs>
Programming in HTML5 with JavaScript and CSS3 11-19
Demonstration: Usin
ng SVG Trransforma
ations and
d Events
De
emonstration Steps
Traansform SVG Elements
2. On the Win
ndows taskbarr, click Interne
et Explorer.
o The <transform> elements transslate the square by 200 units in the X and
d Y axes, scale
e it by a
factor o
of 0.5, and rottate it.
8. Close the so
ource window
w.
andle Events on
Ha o SVG Eleme
ents
3. Move the m
mouse off the shape. Verify that it revertss to a red fill ccolor with no outline.
4. Hover the mmouse over th he blue shape on the right side of the wiindow. Verify that the shap
pe changes
to a yellow fill color and a dotted gree
en border.
5. Move the m
mouse off the shape. Verify that it revertss to a blue fill color with no
o outline.
Programming in HTML5 with JavaScript and CSS3 11-21
6. Click the red shape. Verify that a message box appears, indicating that the shape represents Alaska.
Close the message box.
7. Click the blue shape. Verify that a message box appears, indicating that the shape represents Hawaii.
Close the message box.
o The <path> elements contain the data that defines the two maps.
o Each <path> element responds to the onmousedown event and uses JavaScript code to display
the appropriate message.
10. In the source window, locate the path:hover CSS rule near the top of the document. This CSS rule
defines the style for all <path> elements when the user hovers over them with the mouse.
Lesson 2
Drawiing Gra
aphics b
by Using the C
Canvas API
A
The Canvas API comprises a < <canvas> ele ement and an associate set of JavaScript functions thaat enable
you to draw shaapes onto the canvas. The C e to SVG graphics and is useful if you
Canvas API is an alternative
waant to perform
m one-off grapphical operatiions in a web page. Howevver, whereas SV VG graphics aare defined
byy using HTML5 5 elements, th
he Canvas API is programm matic and requuires you to drraw graphics by
b writing
JavvaScript code..
Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:
• Apply transsformations an
nd animationss to canvas drrawings.
P
Programming in HTM
ML5 with JavaScript and CSS3 11-23
3
W
What is th
he Canvass API?
Ussing the C
Canvas AP
PI
To
o use the Canvvas API, the firrst step is to aadd a <canvas> element to
o your web pa
age. You can also define
aC
CSS style for <
<canvas> elements, if requ uired.
It iis typical to de <canvas> element, so that you can locate it easily in JJavaScript
efine an id atttribute on a <
code by calling a DOM function such as do ocument.gettElementById d(). It is also q
quite common n to define
fallback contentt between the e <canvas> sttart tag and the </canvas> > end tag; thiis content will be
dissplayed by bro owsers that do not recogniize the <canvvas> element.
To
o draw graphiccs on a canvass, you must w
write JavaScrip
pt code. Follow
w these steps:
1. Get a refere
ence to the <ccanvas> elem
ment by calling a DOM funcction such as
document..getElementB ById().
2. Call getCon
ntext('2d') on
n the canvas o
object, to get the two-dime
ensional draw
wing context fo
or the
canvas.
<style>
canvaas {
bborder: 2px solid darkblue;
bbackground-c
color: lightg
green;
}
</style>
…
<h1>Gettiing started with canvas<
</h1>
<canvas iid="myCanvas
s">No canvas support in this browse er</canvas>
<script>
var ccanvas = doc
cument.getElementById('mmyCanvas');
var ccontext = ca
anvas.getContext('2d');
var eedge = 20;
conteext.fillStyle = "red";
conteext.fillRect
t(20, 20, canvas.width - 40, canvas s.height - 40
0);
Programming in HTML5 with JavaScript and CSS3 11-25
</script>
Note that the Canvas API also provides a context.strokeRect() function that draws the outline of a
rectangle but does not fill its interior.
The Canvas API has a range of functions for drawing shapes and lines, including:
Additional Reading: For more information about the full set of functions available in a
canvas two-dimensional context, see http://go.microsoft.com/fwlink/?LinkID=267749.
11-26 Creating Advanced Graphhics
Drawing Paaths
The following exxample showss how to draw w a triangle paath by using tthe Canvas APPI. The triangle
e has a
blu
ue outline color, because th he strokeStylle property is set to rgb(0, 0, 255). The triangle has a semi-
tra
ansparent red fill color, because the fillStyle propertyy is set to rgba
a(255, 0, 0, 0
0.75).
<canvas iid="myCanvas
s">
Sorryy, your brow
wser does not support caanvas.
</canvas>>
<script>
// Get the cannvas element and its draawing contex
xt.
varr canvas = d
document.getElementById(('myCanvas');
varr context = canvas.getCo
ontext('2d'));
// Clear any eexisting content in the canvas.
conntext.clearR
Rect(0, 0, canvas.width,, canvas.height);
// Set the strroke color and the fill color.
conntext.stroke
eStyle = "rgb(0, 0, 255))";
conntext.fillSt
tyle = "rgba(255, 0, 0, 0.75)";
// Create a paath in absolute coordinaates.
conntext.beginP
Path();
conntext.moveTo
o(60, 30);
conntext.lineTo
o(100, 90);
conntext.lineTo
o(20, 90);
// Close the ppath.
conntext.closeP
Path();
// Draw the paath as a stro
oked shape;
conntext.stroke
e();
// Draw the paath as a filled shape.
conntext.fill();
</script>>
P
Programming in HTM
ML5 with JavaScript and CSS3 11-27
7
The triangle d
T drawn by this code looks likke this:
FIGUR
RE 11.1: A TRIIANGLE DRA
AWN BY USIN
NG THE CANV
VAS API
11-28 Creating Advanced Graphhics
• createLineaarGradient()
• createRadiaalGradient()
• createPatte
ern()
Th
he createLin
nearGradie
ent() Function
The createLinea arGradient() function crea ates a linear gradient. creatteLinearGrad dient() has parameters
tha
at define the sstart and end locations of tthe linear graddient, and retturns a linear gradient
g obje
ect. You can
add color stops to the linear gradient by ccalling the add dColorStop()) function. You u can then sett the linear
gra
adient as the ambient fill sttyle or stroke style for a can
nvas context, by setting the e fillStyle or strokeStyle
s
pro
operty. You caan also use th
he gradient to o define the filll color or the stroke color for
f text.
Th
he createRa
adialGradie
ent() Function
The createRadiialGradient() function creaates a radial gradient. creatteRadialGrad dient() has paarameters
tha
at define the ffocal point off the radial gra
adient. You caan add color sstops to the g
gradient and apply
a it to a
context in the saame way thatt you would fo or a linear graadient.
Th
he createPa
attern() Fun
nction
The createPatte
ern() functionn creates a paattern, typically based on an
n image or so
ome other con ntent on the
we
eb page. You ccan apply a pattern
p in the same way tha at you would for
f a linear grradient or a ra
adial
gra
adient.
The following exxample showss how to creatte a linear graadient, a radiaal gradient, an
nd a pattern. T
The pattern
use
ed is based on
n the wales im
mage (this image is the flag g of Wales in the United Kingdom).
<
<canvas id="m
myCanvas">
Sorry, yo
our browser doesn't sup
pport canvas.
<
</canvas>
<
<img id="wale
es" src="Wal
les.png" sty
yle="display: none;" />
<
<script>
// Get th
he canvas el
lement and its drawing c
context.
Programming in HTML5 with JavaScript and CSS3 11-29
T
Transform
ming Shap
pes
• transform
m(scaleX, skeewX, scaleY, skewY,
s transllateX, transla
ateY): Adjustss the current
transform
mation matrix to perform sccaling, skewing, and translaation.
• setTransfform(scaleX, skewX, scale eY, skewY, traanslateX, translateY): Setss a new transfformation
matrix to perform scaliing, skewing, and translatio
on.
Additio
onal Reading: For more infformation abo
out Canvas traansformationss, visit
http://go.micrrosoft.com/fw
h wlink/?LinkID=
=267750.
11-32 Creating Advanced Graphhics
Demonstration: Perfforming T
Transformations by Using the
e Canvas A
API
De
emonstration Steps
Pe
erform Simple Transformations
1. On the Win
ndows 8 Start screen, click the Desktop tile.
2. On the Win
ndows taskbarr, click Interne
et Explorer.
o The . demoSeperate
eTransforma ations function uses the dra
awShape fun
nction to draw
w a triangle
filled with
w an image of the Welsh flag.
o Before calling the drrawShape fun nction, the code transformss the context; it moves the canvas to
the righ
ht and down by half the wiidth and height of the canvvas, then it sca
ales the conte
ext by a
differen
nt value in the
e X and Y dim
mensions, and then rotates the
t context byy PI/4 radianss.
o When the
t drawShap
pe function iss called, the im
mage is transfo
ormed accord
ding to the co
ontext
settings.
omment out e
Note: If time allows, co each of the traansformationss and run the code again.
Then uncomme o that studentts can see the effects of eacch
ent each transfformation one at a time, so
ne.
on
Programming in HTML5 with JavaScript and CSS3 11-33
o This function is similar to the previous one in that it transforms the context and then calls the
drawShape function to display the image.
o The difference is that this function uses the transform function to perform a matrix
transformation, scaling, skewing, and translating the context in a single function call.
Lab: C
Creating
g Advan
nced Graphicss
Sccenario
The conference organizers would like a venue map disp played on the website. Conference attendees will
usee the map to find out more e about the roooms of the conference faccility. Thereforre, the map shhould be
intteractive, resp
ponding to mo ouse clicks. Th
he floor plans are available in a vector fo
ormat, so theyy can be
dissplayed in a reesolution-inde
ependent form mat.
Co
onference speakers need baadges with the eir photo, nam
me, and ID. Th e form of a barcode to
he ID is in the
maake it easy forr security perssonal to scan and
a verify the ntify before alllowing backstage
e holder’s iden
acccess. You havee been asked to create a w web page that enables a spe eaker to creatte their badge
e.
Ob
bjectives
Aftter completing this lab, you
u will be able to:
• phics by using
Create grap g SVG, interacttively style SV
VG graphics, and handle SV
VG graphics evvents.
• Draw graph
hics by using tthe Canvas AP
PI.
Esttimated Time:: 60 minutes
First, you will complete the partially completed SVG mark-up of the venue map. Next, you will add
interactive styling to the SVG by using CSS. Then you will add handle SVG element click events to display
extra information about conference rooms. Finally, you will run the application, view the Location page,
and verify that the venue map is interactive.
The main tasks for this exercise are as follows:
X Task 1: Review the incomplete HTML markup for the venue map
1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-11 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 1
folder.
5. Verify that the page contains an <svg> element of the venue map, and two hidden <div> elements
containing room information.
Also notice that the script references the location-venue.js script in the scripts/pages folder.
6. Run the application and view the Location page. Notice that the details for Room B are missing:
11-36 Creating Advanced Graphhics
X Task 2: Co
omplete the
e SVG venue
e map
1. In the locattion.htm file, add the SVG elements for Room B by using room-b as the group element id.
The missingg elements are e a filled rectaangle and the e name of the room. Use the SVG
e text with the
elements foor Room A as a guide.
Note: You u may need too view the pag ge in Internett Explorer and experiment w
with the
coordinate values to get elem
ments in the ccorrect locatio
on.
X Task 3: Ad
dd interactivity to the v
venue map
1. The venue map
m should b be interactive; a user shouldd be able to view more infoormation abouut a room
by clicking on it in the m
map. In the loccation.htm file
e, find the follo
owing <div> elements. The
ese
elements coontain the infoormation abo out each room m, but they are e hidden by default:
<div id="room-a-info"
" style="dis
splay: none">
>
<h2>Room
m A</h2>
<p>Capacity: 250</p
p>
<p>Popular sessions
s in here:</
/p>
<ul>
<li>Diving in at the deep en
nd with Canvas</li>
<li>Real-world Ap
pplications of HTML5 APIs</li>
<li>Transforms an
nd Animation
ns</li>
</ul>
</div>
<div id="room-b-info"
" style="dis
splay: none">
>
<h2>Room
m B</h2>
<p>Capacity: 230</p
p>
Programming in HTML5 with JavaScript and CSS3 11-37
2. Notice that each <div> is named after the room with the suffix –info.
Note: The information for each room is hard-coded into the HTML markup. However, to
make the page even more dynamic, you could retrieve information about popular sessions from
the web service used in the Schedule page.
3. The room should change color when the mouse moves over it. Open the location.css style sheet in
the styles\pages folder. This style sheet contains CSS for the location.htm page.
4. Add a CSS rule that targets rect elements when the cursor is hovering over .room elements.
5. In this rule, set the fill property to #b1f8b0
6. Open the location-venue.js file in the scripts\pages folder. This JavaScript file contains the
showRoomInfo function that displays information about a room. The id of the room is specified as
the parameter to this function.
7. Add click event listeners for the SVG room elements, which call the showRoomInfo function.
Note: Use the querySelectorAll function of the document object to find all elements that
have the class set to .room.
2. Move the cursor over each room and verify that the fill color changes.
The informa
ation displaye
ed for Room B should look like this:
Reesults: After co
ompleting thiis exercise, you will have a vvenue map th
hat displays exxtra information when
cliccked.
Programming in HTML5 with JavaScript and CSS3 11-39
First, you will create a canvas element on the speaker badge page. Next, you will write JavaScript code to
implement methods that draw parts of the badge. Finally, you will run the application and test the
speaker badge page.
2. Open the speaker-badge.htm file. This page contains a section that enables the user to create their
speaker badge. Previously, you used an <img> element to drag and drop an image of the speaker
onto this page. This <img> element has been removed because you are going to modify the page to
use a canvas instead. Using a canvas provides more scope for customizing the image.
5. Add a solid black border to the canvas by using a CSS style. Set the width to 1px.
data-speaker-id="234724"
data-speaker-name="Mark Hanson"
Note: The custom data attributes provide a convenient way to store application-specific
data in an HTML element. They will be used by the JavaScript code that draws the elements for
the badge on the canvas.
In this exercise, these details are hard-coded into the HTML markup, but you could also write
JavaScript code to dynamically populate these attributes.
Note: The other drawing methods of the speaker badge page object will use the context,
assigned to this.context, to do their drawing.
• Draw the top text (use the drawTopText function; this function simply generates the text
ContosoConf 2012 Speaker ,which is displayed at the top of the badge).
• If the image variable references a valid image, then draw the speaker's image (use the
drawSpeakerImage function and pass the image variable as the parameter), otherwise draw a
placeholder (use the drawImagePlaceHolder function).
• Draw the bar code (use the drawBarCode function and pass the value in the speakerId variable as
the parameter).
5. In the drawSpeakerImage method, draw the image on the canvas at the coordinates (20, 20), with
size 160 × 160. Note that the image is not always square, so calculate the source coordinates and
size that will display the central square portion only. Use the Math.min function to calculate the
minimum of the image’s width and height properties.
7. Configure the following context properties of the canvas properties to style the text before drawing it.
o fillStyle: black.
o textBaseline: top.
o textAlign: left.
2. Drag and drop the mark-hansen.jpg image file from the E:\Labfiles\Resources folder onto the
canvas.
3. Verify that the image is drawn on the canvas, along with the speaker’s details.
P
Programming in HTM
ML5 with JavaScript and CSS3 11-41
1
FIGUR
RE 11.6: THE S
SPEAKER BAD
DGE FOR MA
ARK HANSON
N
4
4. Close Inte
ernet Explorerr.
Modu
ule Reviiew and
d Takea
aways
M
Module Revie
ew
In this module, yyou have seen
n how to use SVG and the Canvas API to
o draw graphical content in
n a web
page.
SV
VG uses a retaiined drawing model, which
h means SVG elements are retained in thhe DOM tree. You can
acccess SVG elem g DOM functiions, you can style SVG elem
ments by using ments by usin
ng CSS style ru
ules, and
you can handle user-interaction events on
n SVG elementts.
The Canvas API uses a fire-annd-forget drawwing model, w
which means shapes are drrawn on the ca anvas but
aree not retained
d in the DOM tree. You cannnot access shapes in a canvvas by using D
DOM function ns, or style
thee shapes, or h
handle any eveents on them.. Nonetheless, the Canvas A
API is very use
eful if you nee
ed to draw
staatic graphical images on the web page.
Q
Question
W
Which of the ffollowing statements abou
ut SVG is false?
S
Select the corrrect answer.
Question: When
W might yyou consider using the Can
nvas API insteaad of using SV
VG?
12-1
Module 12
Animating the User Interface
Contents:
Module Overview 12-2
Modu
ule Ove
erview
An
nimations are a key elemen
nt in maintainiing the interest of a user in
n a website. Im
mplemented carefully,
animations improve the usab
bility of a web page and pro ovide useful vvisual feedbacck on user actiions.
This module desscribes how to o enhance we eb pages by using CSS anim mations. You wwill learn howw to apply
tra
ansitions to prroperty valuess. Transitions enable
e you too specify the timing of for property
p channges. For
exaample, you caan specify that an element should chang ge its width annd height ove
er a five-secon nd period
whhen the mouse e pointer hovvers over it. Ne
ext, you will le
earn how to apply 2D and 3 3D transformaations to
ele
ements. Transformations en nable you to sscale, translatee, rotate, and skew elements. You can also apply
tra
ansitions to tra
ansformationss, so that the transformatio on is applied ggradually overr a specified aanimation
peeriod.
At the end of th
his module, yoou will learn hhow to apply kkeyframe anim mations to ele
ements. Keyfraame
animations enab ble you to deffine a set of p
property valuees at specific moments
m during an animattion. For
exaample, you caan specify the color and po osition of an element at 0 ppercent, 33 peercent, 66 perccent, and
10
00 percent of the
t animation n period.
Ob
bjectives
Aftter completing this module
e, you will be able to:
Lesson 1
Appllying CS
SS Tran
nsitionss
Transitions en
T nable you to specify the tim meframe for property value changes. Transitions impro ove the user
i
interface by m
making property changes sm mooth and grraceful, insteaad of suddenlyy changing fro
om one value e
t another. In this lesson, yyou will learn how
to h to implem
ment transitio ons by using C
CSS.
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Apply sim
mple transition
ns to element property valu
ues by using C
CSS.
• Configure
e transition in
nformation.
• Detect th
he end of a tra
ansition.
12-4 Animatiing the User Interfacce
Ap
pplying Siimple Transitions b
by Using CSS
C
Whhen you definne CSS style ru ules for elemeents, the style rules apply im
mmediately byy default. For example,
the
e following styyle rules speccify that <div>
> elements will have a widtth of 300px no ormally, but a width of
60
00px when the e user hovers over them. Th he change from 300px to 6 600px will take
e effect as soo
on as the
use
er hovers oveer a <div> ele ement. Likewisse, the reversee change from m 600px to 3000px will take effect
immediately as the user movves the mouse e away from th he <div> elem ment:
div {
width
h: 300px;
}
div:hover
r {
width
h: 600px;
}
• The duratio
on of the transsition.
The following exxample showss the same styyles as before,, except that the
t width of <
<div> elemen
nts will
change over a period
p of two seconds when the mouse movesm over thhem. When th
he mouse movves away,
the
e reverse transition is autom
matically appllied over the same
s period.
div {
width
h: 300px;
trans
sition: widt
th 2s;
}
div:hover
r {
width
h: 600px;
}
If yyou want to aapply multiple e transitions simultaneouslyy, specify a comma-separated list of CSS property
names and duraations for the transition prroperty. The fo ollowing exammple defines ttransitions forr various
CSSS properties ffor <div> elements. When the user hove ers over a <div>, the widtth, height, and font-size
pro operties transsition to their new values inn two secondss, and the bacckground-collor property ttransitions
to its new value e in 3750 millisseconds. Whe en the user mo
oves the mouse away from m a <div>, the e width,
Programming in HTML5 with JavaScript and CSS3 12-5
height, and font-size properties transition to their original values in two seconds, and the background-
color property transitions to its original value in 3750 milliseconds:
div {
width: 400px;
height: 60px;
background-color: yellow;
transition: width 2s, height 2s, font-size 2s, background-color 3750ms;
}
div:hover {
width: 600px;
height: 80px;
font-size: large;
background-color: red
}
Co
onfiguring
g Transitio
ons
If yyou want to aapply multiple e transitions simultaneouslyy, specify a comma-separated list of valu ues for each
tra
ansition prope erty. For exammple, if you waant to animatee the width, h height, and fon nt size, specifyy
traansition-prop perty: width, height, fontt-size. If you wwant the width and height transitions to o last two
secconds, and the font size traansition to thrree seconds, specify transittion-duration n: 2s, 2s, 3s. If you
spe ecify fewer vaalues than the e number of properties
p beinng transitione ed, the final vaalue is repeateed for the
rem maining properties. For exaample, if you sspecify transiition-propertty: width, heiight, font-sizze and you
spe ecify transitioon-duration: 2s, 3s, then tthe width tran nsition will takke two second ds and the heiight and
fon nt size transitiion will both take
t three secconds.
The following exxample define es transitions for various CSSS properties for <div> eleements. The eexample
animates the wiidth, height, font-size, and backgroun nd-color CSS properties forr a <div> whe en the user
hoovers over it. T
The width, he
eight, and fon o seconds to ccomplete, and the
nt-size transittions take two
baackground-co olor property takes 3750 milliseconds
m o complete. All of the transitions use an e
to ease-in
tim
ming function,, and there is a delay of one second befo ore the transittions commen nce.
Programming in HTML5 with JavaScript and CSS3 12-7
div {
width: 400px;
height: 60px;
background-color: yellow;
transition-property: width, height, font-size, background-color;
transition-duration: 2s, 2s, 2s, 3750ms;
transition-timing-function: ease-in;
transition-delay: 1s;
}
div:hover {
width: 600px;
height: 80px;
font-size: large;
background-color: red
}
12-8 Animatiing the User Interfacce
Detecting the
t End off a Transittion
Wh hen a transitio
on has finishe
ed, a transitio
onend event iss fired on the element with h the propertie es that
have been transsitioned. This event is usefuul if you need to implementt functionalityy that runs on nly when a
tra
ansition has coompleted, succh as impleme enting a seriess of animation ns. If you applly multiple traansitions to
the
e same eleme ent, a separate
e transitionen nd event is firred for each trransition when it ends.
• propertyName: The nam me of the CSSS property for which the traansition has co
ompleted, succh as width,
height, or ffont-size.
<script>
functtion onLoad(
() {
vvar divEleme
ents = document.querySel
lectorAll("d
div");
ffor (var i = 0; i < divElements.len
ngth; i++) {
divEleme
ents[i].addEv
ventListener
r("transitio
onend", onTransitionend,
, true);
}
}
var mmessagesElem
ment = document.querySel
lector("mess
sages");
functtion onTrans
sitionend(e) {
mmessages.add
d(new Option(e.propertyN
Name + ", elapsedTime " + e.elapsed
dTime));
}
</script>>
...
<body onlload="onLoad
d()">
<div class="simpple">Hover here to see s
simple trans
sitions</div>
>
<div class="compplex">Hover here to see complex tra
ansitions</div>
<seleect id="mess
sages"></select>
</body>
Programming in HTTML5 with JavaScrippt and CSS3 12-9
9
D
Demonstr
ration: Ussing CSS T
Transitionss
D
Demonstra
ation Steps
A
Apply CSS Traansitions to HT
TML Elementss
1
1. On the W
Windows 8 Sta
art screen, clicck the Deskto
op tile.
2
2. On the W
Windows taskb
bar, click Interrnet Explorerr.
3
3. In Interne
et Explorer, op
pen the file E:\Democode\\Transitions.h
html.
4
4. y want to allow blocked content, click the Allow blocked
If a messaage box appears asking if you
content b button.
5
5. Hover over the upper rectangle on tthe web page
e. Verify that tthe following transitions are
e applied
simultane
eously to the rrectangle:
6
6. Move the
e mouse awayy from the upp per rectangle.. Verify that th
he rectangle rreverts to its original
o
appearan
nce, over the ssame period of
o time.
7
7. Repeat th
he previous tw
wo steps for th
he second recctangle. Verifyy that the sam
me animations apply.
8
8. Right-clicck the page in
n Internet Expllorer and then
n click View source.
s Note tthat:
o The d
div.simple rule defines a trransition pro
operty that applies to transitions on the w
width,
height, font-size, and backgro ound-color C CSS propertiess.
o The d
div:hover rulee defines the final values fo
or the width, height, font--size, and bacckground-
colorr CSS properties when the user hovers o over a <div>.
H
Handle the trransitionend Event
12-10 Animating the User Interface
1. In Internet Explorer, expand the drop-down list box. Verify that it displays messages for all the
transitions that have ended. The list includes events for the original transitions when you hover over a
rectangle, as well as events for the reverse transitions when you move the mouse away from a
rectangle.
o The onLoad() function sets up event-handlers for the transitionend event on all the <div>
elements.
o The onTransitionend() function displays information about the transitionend event, by using
the propertyName and elapsedTime properties of the event argument.
Lesson 2
Transsformin
ng Elem
ments
CSS transform
C mations enable e you to applyy 2D and 3D ttransformations to elementts. You can appply
t
translations, rotations, scaliing, and skew
wing transform
mations. You can also speciffy 3D-related
t
transformatio n properties ssuch as a persspective and b
back-face visib
bility.
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Apply 2D
D transformatio
ons to elemen
nts by using C
CSS.
• Apply 3D
D transformatio
ons to elemen
nts by using C
CSS.
Ap
pplying Transformaations by Using CSS
S
CSSS provides the transform property thatt you can use with a style ru
ule to enable you perform 2D and 3D
tra
ansformationss on an element on a web ppage. When yyou set the tra ansform prop perty, you can specify
onne or more of the following
g transformatio
on functions:
• translate(), ttranslate3d(), translateX(), translateY(),
t and translateZ(): Translate th
he element in
n 2D or 3D
space.
• ale3d(), scaleX
scale(), sca X(), scaleY(), and scaleZ():: Scale the ele
ement in 2D o
or 3D space.
• rotate(), ro
otate3d(), rottateX(), rotatteY(), and rottateZ(): Rotate
e the elementt in 2D or 3D space.
• skew(), ske
ewX(), and sk
kewY(): Skew the element aalong the X-axxis or along th
he Y-axis.
• matrix(), matrix3d():
m Pe
erform a 2D o
or 3D transform
mation by using a matrix to
o specify the
transformattion.
• perspective
e(): Define a perspective
p fo
or an elementt that has been transformed
d in 3D.
• none(): Can
ncel any transsformations th
hat apply on aan element.
Ap
pplying a CSS
S Transforma
ation
<
<!DOCTYPE htmml>
<
<html>
<head>
<meta c
charset="utff-8" />
<style
e>
b
button {
font-fam
mily: verdan
na, arial;
width: 3
300px;
height: 40px;
backgrou
und-color: y
yellow;
border-r
radius: 5px;
transfor
rm: translat
te(60px, 100p
px) skew(45d
deg);
}
</sty
yle>
</head>
<body>
P
Programming in HTM
ML5 with JavaScript and CSS3 12-13
3
<bu
utton type="
"button">Click Me</butto
on>
</body>
>
</html>
T button lo
The ooks like this w
when it is rend
dered by a bro
owser:
FIGUR
RE 12.1: THE T
TRANSFORM
MED BUTTON
N
Additio
onal Reading: For detailed information aabout CSS traansformations, visit
http://go.micrrosoft.com/fw
h wlink/?LinkID=
=267753
12-14 Animaating the User Interfface
Ap
pplying 2D Transfo
ormations
• Scale
• Rotate
• Skew
Trranslating Elements
E
To
o perform a 2D
D translation, use one of th
he following fu
unctions:
• translate(tx,, ty)
• translateX(ttx)
• translateY(tty)
No wing points about the tx and ty parameters:
ote the follow
The following CSS rule translates a <div> element with the class translate1. The element is translated 60
pixels to the right:
div.translate1 {
transform: translate(60px);
}
Scaling Elements
To perform a 2D scaling transformation, use one of the following functions:
• scale(sx, sy)
• scaleX(sx)
• scaleY(sy)
• sx specifies a horizontal scaling factor. A value of 1.0 represents the normal scale.
• sy specifies a vertical scaling factor. A value of 1.0 represents the normal scale. If you call scale() and
omit the sy parameter, the default value for sy is the same as the value you specified for sx.
The following CSS rule scales a <div> element with the class scale1. The element is 30 percent larger in
all dimensions:
div.scale1 {
transform: scale(1.3);
}
Rotating Elements
To perform a 2D rotation, use the following function:
• rotate(angle)
Note the following points about the angle parameter:
• angle specifies the angle of rotation anticlockwise (if negative) or clockwise (if positive) about the
transformation origin. You can specify the angle in degrees or radians.
The following CSS rule rotates a <div> element with the class rotate1. The element is rotated 10 degrees
clockwise about its top left corner:
div.rotate1 {
transform: rotate(10deg);
transform-origin: left top;
}
Skewing Elements
To perform a 2D skewing transformation, use one of the following functions:
• skew(anglex, angley)
• skewX(anglex)
• skewY(angley)
Note the following points about the anglex and angley parameters:
• anglex specifies a skew angle about the X axis as a clockwise skew (if negative) or an anticlockwise
skew (if positive).
12-16 Animating the User Interface
• angley specifies a skew angle about the Y axis as a clockwise skew (if negative) or an anticlockwise
skew (if positive). If you call skew() and omit the angley parameter, the default value for angley is 0.
The following CSS rule skews a <div> element with the class skew1. The element is skewed by 30 degrees
anticlockwise about the X axis:
div.skew1 {
transform: skew(30deg);
}
P
Programming in HTM
ML5 with JavaScript and CSS3 12-17
7
D
Demonstr
ration: Pe
erforming 2D Transsformation
ns
IIn this demon nstration, you will see how tot perform 2D D transformations by using CSS. You will see how to
a
apply translattions, scaling ttransformations, rotations, and skewing transformatio
ons. You will aalso see the
e
effect of channging the origin of transformation.
D
Demonstra
ation Steps
P
Perform 2D Translations
1
1. On the W
Windows 8 Sta
art screen, clicck the Deskto
op tile.
2
2. On the W
Windows taskb
bar, click Interrnet Explorerr.
3
3. In Interne
et Explorer, op
pen the file E:\Democode\\2DTranslatio
ons.html.
4
4. y want to allow blocked content, click the Allow blocked
If a messaage box appears asking if you
content b button.
5
5. Verify thaat the browser displays a se ngles. Each recctangle demonstrates how to perform a
eries of rectan
2D translaation by using eX(), or translateY() functiions. The text message
g the translatte(), translate
inside eacch rectangle d
describes the transformatio on for that recctangle.
6
6. Right-clicck in the brow
wser window, aand then clickk View source
e.
7
7. In the sou
urce window, scroll down to o the bottom of the docum
ment. Note that the body oof the
documen nt has a series of <div> elements, and ea
ach element h
has a distinct CSS class.
8
8. Scroll bacck up to the to
op of the code and locate tthe <style> eelement. The C
CSS rules imp
plement
ons for all the <div> eleme
translatio ents. The CSS rules
r set the standard
s transsform properrty, as well as
the follow
wing vendor-sspecific propeerties:
• -ms-tran
nsform: Perform a transform
mation on Internet Explore
er 9.
• -o-transfform: Perform
m a transformaation on Opera browsers.
9
9. Close the
e source windo
ow.
P
Perform 2D Sccaling Transfo
ormations
12-18 Animating the User Interface
2. Verify that the browser displays a series of rectangles. Each rectangle demonstrates how to perform a
2D scaling transformation by using the scale(), scaleX(), or scaleY() functions. The text message
inside each rectangle describes the transformation for that rectangle.
5. Scroll back up to the top of the code and locate the <style> element. The CSS rules implement
scaling transformations for all the <div> elements. The CSS rules set the standard transform
property, as well as vendor-specific properties.
2. Verify that the browser displays a series of rectangles. Each rectangle demonstrates how to perform a
2D rotation by using the rotate() function. The fourth rectangle also shows how to perform multiple
transformations, and how to change the origin of the transformation to the top left of the target
element.
3. Right-click in the browser window, and then click View source.
4. In the source window, scroll down to the bottom of the document. Note that the body of the
document has a series of <div> elements, and each element has a distinct CSS class.
5. Scroll back up to the top of the code and locate the <style> element. The CSS rules implement
rotations for all the <div> elements. The CSS rules set the standard transform property, as well as
vendor-specific properties. The final CSS rule shows how to apply multiple transformations,
specifically a translation followed by a rotation. The final CSS rule also shows how to set change the
origin of the transformation by setting the transform-origin property and its vendor-specific
equivalent properties.
6. Close the source window.
5. Scroll back up to the top of the code and locate the <style> element. The CSS rules implement
skewing transformations for all the <div> elements.
A
Applying 3D Transfformation
ns
CSS3 providess a set of funcctions that also enable you to perform trransformation
C ns in 3D space
e. These
f
functions are similar to their 2D counterrparts, but gen
nerally take an
n additional p
parameter speecifying the Z
d
dimension. Th
his topic descrribes how to pperform the fo
ollowing 3D transformation ns:
• Translatio
on
• Scaling
• Rotation
T
Translating
g Elements
T perform a 3D translation, use one of the following
To g functions:
• translate3
3d(tx, ty, tz)
• translateZ
Z(tz)
The tz parame
T on in the Z axis, which is perpendicular to
eter specifies the translatio o the plane off the screen.
Y must specify an absolu
You ute value, rath he translate3d() function, the ty and tz
her than a perrcentage. In th
p
parameters arre optional; th
hey both default to 0.
S
Scaling Elem
ments
T perform a 3D scaling traansformation,, use one of th
To he following ffunctions:
• scaleZ(sz))
R
Rotating Ellements
T perform a 3D rotation, u
To use the follow
wing function:
• rotate3d((xnum, ynum, znum, angle))
• Set the perspective CSS property on the parent element, to apply the perspective to each of the child
elements.
You can also set the perspective-origin CSS property to shift the viewpoint away from the center of the
element.
The following example shows how to define perspective for a 3D transformation. The example defines
<div> elements named child1 and child2 in a parent element named parent. Note the following CSS
rules:
• The #parent CSS rule defines a perspective of 300px, which means the disappearing point will be
300 pixels to the right of the perspective origin. The perspective-origin property moves the
perspective origin 100 pixels to the left and 50 pixels upwards.
• The #child1 CSS rule rotates a <div> element by 30 degrees clockwise about the Y axis.
• The #child2 CSS rule rotates a <div> element by 30 degrees clockwise about the Y axis, and then
translates the shape by 250 pixels in the X direction.
<style>
#parent {
perspective: 400px;
perspective-origin: -100px -50px;
}
#child1 {
background-color: orange;
position: absolute;
transform-origin: 0px 0px;
transform: rotateY(30deg);
}
#child2 {
background-color: orange;
position: absolute;
transform-origin: 0px 0px;
transform: rotateY(30deg) translate(250px);
}
</style>
...
<div id="parent">
<div id="child1">This is child1</div>
<div id="child2">This is child2</div>
</div>
P
Programming in HTM
ML5 with JavaScript and CSS3 12-21
1
FIGUR
RE 12.2: REND MENTS WITH A 3D PERSP
DERING ELEM PECTIVE
12-22 Animaating the User Interfface
Yo
ou can define a transition fo
or transformattions, so that the transform
mation is appliied gradually over a
spe
ecified time p
period. To define a transitio
on for a transfo
ormation, folllow these step
ps:
• Define a 2D
D or 3D transfo
ormation for an element by using the trransform CSSS property.
The following exxample define es a rotation ffor a <div> element name ed container. When the use er hovers
ovver the elemen nt, the elemen
nt will rotate b
by 90 degreess clockwise. Th he example allso defines a ttransition
forr the transform
mation, so thaat the rotation
n will take five
e seconds to ccomplete:
<style>
#conttainer {
ttransition: transform 5s;
}
#conttainer:hover
r {
ttransform: r
rotate(90deg);
}
</style>
...
<div id=""container">
>
...
</div>
P
Programming in HTM
ML5 with JavaScript and CSS3 12-23
3
D
Demonstr
ration: Pe
erforming 3D Transsformation
ns
IIn this demon nstration, you will see how to D transformations. You will also see how
t perform 3D w to define a
t
transition for a transformattion.
D
Demonstra
ation Steps
P
Perform 3D Transformation
ns that Include Transitions
1
1. On the W
Windows 8 Sta
art screen, clicck the Deskto
op tile.
2
2. On the W
Windows taskb
bar, click Interrnet Explorerr.
3
3. In Interne
et Explorer, op
pen the file E:\Democode\\3DTransform
mations.html.
4
4. y want to allow blocked content, click the Allow blocked
If a messaage box appears asking if you
content b button.
5
5. Verify thaat the browser displays a cu
ube. There aree six faces to tthe cube, eachh of which dissplays text
and has a different bacckground colo or. The front fface is partiallyy transparent, so that it does not
complete ely obscure the other faces.
6
6. Hover over the cube. Verify
V that it ro degrees over a period of fivve seconds. Th
otates by 90 d hen move the
e
mouse offf the cube, an
nd verify that the cube rotaates smoothlyy back to its orriginal positio
on.
7
7. Right-clicck in the brow
wser window, aand then clickk View source
e.
8
8. In the sou
urce window, scroll down to o the bottom of the docum ment. Note that the body oof the
documen nt has six <div
v> elements tthat representt the six faces of the cube. These
T <div> elements are
containedd in a parent <div> elemen nt named con ntainer.
9
9. Scroll bacck up to the to
op of the code and locate tthe <style> e
element. Note
e the following
g CSS rules:
• #rightFace: Transform
ms the rightFa
ace element in
n 3D space, so
o that it appeaars on the righ
ht side of the
cube.
12-24 Animating the User Interface
• #leftFace: Transforms the leftFace element in 3D space, so that it appears on the left side of the
cube.
• #topFace: Transforms the topFace element in 3D space, so that it appears on the top of the cube.
• #bottomFace: Transforms the bottomFace element in 3D space, so that it appears on the bottom of
the cube.
• #backFace: Transforms the backFace element in 3D space, so that it appears at the back of the cube.
• #frontFace: Transforms the frontFace element in 3D space, so that it appears at the front of the
cube. The background color is partially transparent.
10. Close the source window.
Lesson 3
Appllying CS
SS Keyfframe A
Animations
CSS keyframe
C e animations enable
e you to define an aniimation as a series
s of steps. For each step, or
k
keyframe, you
u can define a set of property values that you want to
o apply at thatt stage in the animation.
W
When the bro
owser perform
ms the animatiion, it interpolates propertyy values between the keyfraames, to give
y the effectt of a smooth transition bettween values..
you
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Define ke
eyframes for C
CSS animation
ns.
• Configure
e keyframe an
nimation prop
perties.
• Handle th
he events thatt occur during
g a keyframe animation.
a
12-26 Animaating the User Interfface
Defining a Keyframe
e Animatio
on
To
o use keyframe e animations in a web page e, the first step is to define a @keyframes CSS rule. W Within this
rulle, you define a series of rule-sets that apply at differe ent points durring the animation. These p points are
speecified as perccentages of thhe elapsed tim
me of the dura ation of the animation. The e first rule-set is
de
esignated by the value 0% or o from. The final rule-set is designated by the value 100% or to. Y You can
efine as many rule-sets as you want, and the ordering of the rule-se
de ets is irrelevan
nt.
The following exxample define es a keyframee animation naamed ballmo ovement. The keyframe aniimation has
fouur rule-sets, w
which describee the color and location of a ball on a po
ool table durin
ng an animatiion; the ball
alsso changes co olor as it move
es:
@keyframees ballmovemment {
0% {
lleft: 0px;
ttop: 0px;
bbackground-ccolor: yellow
w;
}
33% {
lleft: 100px;
ttop: 160px;
}
66% {
lleft: 200px;
ttop: 0px;
}
100% {
lleft: 300px;
ttop: 160px;
bbackground-ccolor: purple;
}
}
Programming in HTML5 with JavaScript and CSS3 12-27
Note: Most browsers currently do not support the standard keyframes CSS rule name.
Instead, you must use vendor-specific prefixes such as @-ms-keyframes for Microsoft Internet
Explorer 10.
You perform the animation by specifying the animation-name property in a style rule. This property
expects the name of the keyframe animation, like this:
#ball.animate {
animation-name: ballmovement;
}
In this example, any elements named ball that have the class animate will be animated.
Note: You can write JavaScript code to apply the animate class to the ball when you want
the animation to play. You can also write JavaScript code to remove the animate class from the
ball when you want the animation to stop.
Additional Reading: For detailed information about CSS animations, visit
http://go.microsoft.com/fwlink/?LinkID=267754.
12-28 Animaating the User Interfface
Co
onfiguring
g Keyfram
me Animattion Prope
erties
• animation--name: The n
name of the an
nimation that you want to apply to the ttarget elemen
nt.
• animation--duration: Th
he duration off the animatio
on.
• animation--delay: An op
ptional delay tthat occurs be
efore the anim
mation starts.
• animation--timing-funcction: Optionaal information n about how tthe animationn progresses o over one
cycle. Possib ease-in-out". The
ble values include "linear"", "ease", "easse-in", "ease-out", and "e
default valu
ue is "ease". Y
You can define ole animation, or just for specific steps
e this property for the who
in the @key yframe animaation definitioon.
• animation--iteration-co
ount: Optional iteration cou
unt. The defau
ult value is 1.
• animation--direction: Optional inform mation about the direction the animation should playy. The
default valuue is normal, which means the animation always playys in forward d direction from
m start to
end. The otther possible vvalue is altern
nate, which m
means the anim es itself each time it
mation reverse
plays if the iteration coun
nt is more thaan 1.
The following exxample config gures keyfram me animation ffor an elemen nt named balll that has a CSSS class
named animate e. The examplle applies a ke eyframe animation named ballmoveme ent. The animaation will
lasst 10 seconds and will start after an initiaal delay of three seconds. TThe animation will use a line
ear timing
funnction, which causes the brrowser to inte erpolate values linearly betwween keyfram
me steps. The aanimation
will play twice; tthe first cycle will be in the forward direcction, and the
e second cycle
e will be in the
e reverse
dirrection:
Programming in HTML5 with JavaScript and CSS3 12-29
#ball.animate {
animation-name: ballmovement;
animation-duration: 10s;
animation-delay: 3s;
animation-timing-function: linear;
animation-iteration-count: 2;
animation-direction: alternate;
}
Note: As with keyframes rules, most browsers currently do not support the standard
property names for keyframe animations. Instead, you must use vendor-specific prefixes such as -
ms-animation-name and -ms-animation-duration for Microsoft Internet Explorer 10.
12-30 Animaating the User Interfface
Sttarting a K
Keyframe Animation Program
mmatically
y
<style>
...
@keyfframes ballmmovement {
....
}
#balll.animate {
aanimation-naame: ballmovement;
....
}
</style>
...
<script>
functtion startAnnimation() {
vvar ball = ddocument.getElementById(("ball");
bball.classList.add("anim mate");
}
</script>>
...
<body>
...
<div id="ball">< </div>
<buttton id="buttton" onclick=="startAnima
ation()">Sta
art Animation</button>
...
</body>
P
Programming in HTM
ML5 with JavaScript and CSS3 12-31
1
H
Handling Keyframe
e Events
T
Three occur when a keyframe animation runs. These events are:
events o
• animatio
onstart: Indicaates that a keyyframe anima
ation has startted.
• animatio
oniteration: In
ndicates that an iteration o
of the keyfram
me animation has completed.
• animatio
onend: Indicattes that a keyframe animattion has ended
d.
IIf you handle these events, the event-haandler function will receive an event argu
ument that haas the
f
following properties:
• animatio
onName: The name of the animation, su
uch as ballmo
ovement in th
he previous exxamples.
• elapsedTTime: The totaal elapsed tim
me of the anim
mation so far, e
excluding anyy delay before
e the
animation
n started.
<script
t>
...
var
r ball = document.getEle
ementById("b
ball");
// Handle the event that o
occurs when the ball animation star
rts.
ball.addEventListener("MSA
AnimationSta
art", function (e) { ... }, false);
// Handle the event that o
occurs for each
e iteration.
ball.addEventListener("MSA
AnimationIte
eration", function (e) { ... }, fal
lse);
// Handle the event that o
occurs when the ball animation ends
s.
ball.addEventListener("MSA
AnimationEnd
d", function (e) { ... }
}, false);
...
</scrip
pt>
Note: In
nternet Explorrer 10 uses the names MSA
AnimationSta
art, MSAnima
ationIteration,
a MSAnimationEnd forr these events..
and
12-32 Animaating the User Interfface
Demonstration: Imp
plementing KeyFram
me Animaations
In this demonstration, you wiill see how to define a keyfframe animation and applyy the animatio
on to an
HTTML element. You will also see how to co ontrol the animation progrrammatically, and how to hhandle
keyyframe animaation events.
De
emonstration Steps
De
efine and Run a Keyframe Animation
A
5. Verify that a green rectangle appears on the page, with a small w white circle in the top left ccorner. The
green rectaangle represennts a pool table and the wh
hite circle reprresents a ball. There is also a button
that enablees you to start the animation.
6. Click Start A
Animation.
o After th
hree seconds, the ball startss moving diag
gonally on the
e pool table. T
The color of th
he pool
table also changes too blue, and a message app pears at the bo
ottom of the ppage to indicaate the start
time off the animatio
on.
o When the
t ball reaches the bottom m right cornerr of the pool ttable, a messa age appears to o indicate
that the
e first iteration of the anim
mation has com mpleted. The next
n iteration of the animation
n plays the aniimation in revverse, so that tthe ball ends up in its original
begins;; this iteration
position and with itss original colo
or.
o At the e
end of the an
nimation, the p
pool table revverts to green and a messag
ge appears att the
bottomm of the page to indicate th
he elapsed tim
me of the animmation.
Programming in HTML5 with JavaScript and CSS3 12-33
8. In the source window, scroll down to the bottom of the document. Note that the body of the
document has a <div> element named pooltable that represents the pool table, and a nested <div>
named ball that represents the ball on the pool table. There is also a <button> element to start the
animation, and a <div> where messages can be displayed.
9. Scroll back up to the top of the file and locate the <style> element. Note the following CSS rules:
o #pooltable.animate: Specifies a different color for the pool table during an animation. There is
JavaScript code elsewhere in the document that programmatically adds the animate class to the
pooltable element when an animation starts, to cause the pool table to turn blue during an
animation.
o #ball: Specifies the initial appearance of the ball.
o #ball.animate: Applies the ballmovement keyframe animation to a ball when the ball has the
animate class. There is JavaScript code elsewhere in the document that programmatically adds
the animate class to the ball element when the user clicks the Start Animation button, to
trigger the animation.
10. Locate the <script> element. Note that:
o The init() function, invoked as soon as the page has loaded, establishes event-handler functions
for the MSAnimationStart, MSAnimationIteration, and MSAnimationEnd events on the ball
element:
o The MSAnimationStart event-handler function is called when an animation starts on the ball
element. The function adds the animate class to the pool table, so that the pool table becomes
blue. The function also displays a message to indicate the time when the animation started.
o The MSAnimationEnd event-handler function is called when an animation ends on the ball
element. The function enables the button, removes the animate class from the ball and the pool
table, and displays a message to indicate the elapsed time of the animation.
o The startAnimation() function is Invoked when the user clicks the Start Animation button. The
function disables the button, and adds the animate class to the ball to trigger the animation. The
animation starts three seconds later, due to the -ms-animation-delay: 3s; property in the
#ball.animate CSS rule.
Lab: A
Animatiing the User In
nterface
e
Sccenario
Yo
ou have been asked to makke the Contoso
o Conference web site morre engaging b
by adding som
me
animation.
ou decide to animate the Re
Yo egister link, d
displayed on tthe Home pag
ge. When the
e user moves tthe mouse
ovver this link, yo
ou will make it rotate slighttly to highligh
ht it.
Ob
bjectives
Aftter completing this lab, you
u will be able to:
• TML elementss by using CSSS transitions.
Animate HT
• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 12-35
First you will animate the star icons on the Feedback page so they react when moving the cursor over
them. Next, you will rotate the Register link on the Home page as the mouse traverses it. Finally, you will
run the application, view the Feedback and Home pages, and verify that the elements are animated
correctly.
The main tasks for this exercise are as follows:
3. Start Visual Studio and open the ContosoConf.sln solution from the E:\Labfiles\Starter\Exercise 1
folder.
4. In the ContosoConf project, examine the contents of the feedback.htm file. This page contains an
HTML form that collects conference attendee feedback. This page also references the feedback.css
style sheet in the /styles/pages folder, and the feedback.js JavaScript file in the /scripts/pages
folder.
6. Note that the input elements for the form have been converted into star icons. This feature is
implemented by the JavaScript code in the feedback.js and StarRatingView.js files.
2. Add a CSS property to the .star:hover, .star.hover rule that transforms the stars to be 1.3 times
larger when the mouse moves over them.
3. Specify that the transformation should take 0.5 seconds to perform.
4. When the mouse is no longer hovering over a star, the star should not suddenly jump back to its
original size, so add a transition to the .star CSS rule that reverts the star back to its original size over
0.5 seconds.
5. When a star has the .selected CSS class, it should remain scaled. Add a transform to the
.star.selected rule that scales the star by a factor of 1.3.
• Rotate the link to 16 degrees and scale it by a factor of 1.1 in both dimensions.
4. Move the mouse over the Register Free link in the header and verify that it rotates and enlarges.
Results: After completing this exercise, the Register button will rotate and the feedback stars will animate
when the mouse moves over them.
Programming in HTML5 with JavaScript and CSS3 12-37
First, you will define a keyframe animation by using CSS. Next, you will use the keyframe animation in a
CSS rule. Then you will add this CSS rule to the Feedback form to trigger the animation when the form is
submitted. You will handle an animation event to show a message when the animation is complete.
Finally, you will run the application, view the Feedback page, and verify that the form animates correctly
when the user submits it.
2. In the feedback.css style sheet in the styles\pages folder, define a keyframe animation named send.
The animation should perform the following operations:
• Reduce the size of the targeted element, using a scale transform, to be 0.8 times the original size.
• Slide the target element up off the page. A translation of 1000px up is enough to move the feedback
form out of view.
3. The sending CSS class will be added to the feedback form when it is submitted (you will write the
JavaScript code to do this in the next task). In the feedback.css style sheet, add CSS properties to the
.sending rule that apply the send animation:
• Set the animation duration to be one second.
• Ensure that the animation runs only once, and that it maintains the properties set by the last
keyframe after completion.
2. A submit event listener has already been added to the feedback form. This event listener calls the
formSubmitting function. In the formSubmitting function, add the CSS class sending to the form
element.
Note: Adding this class to the form element triggers the animation that you defined in the
previous task
3. After the feedback form has finished animating, the feedback-sent div in the Feedback form should
be displayed. This div displays the message Thanks for the feedback. The animationEnded function
displays this div. Add an animationend event listener to the form, which calls animationEnded.
3. Verify that the form shrinks and flies off the top of the page.
Results: After completing this exercise, submitting the conference feedback form will trigger an animation
that makes the form fly off the page.
P
Programming in HTM
ML5 with JavaScript and CSS3 12-39
9
Module Rev
view an
nd Take
eaways
M
Module Rev
view
IIn this module
e, you have le
earned how too create anima
ated content by using CSS3
3 transitions,
t
transformatio ns, and keyfraame animatio
ons.
CSS transition
C ns enable you to define a time span for p property chan nges. The browwser interpola
ates the
p
property from ue to its final value over the specified tim
m its initial valu me span, to give the user th
he effect of a
s
smooth transiition from the e original prop perty value to
o the new prop perty value.
CSS transform
C mations enable e you to transslate, scale, rottate, or skew an element. CSS
C supports 2 2D
t
transformatio ns in the X an
nd Y directions, and 3D tran nd Z directions.
nsformations in the X, Y, an
CSS keyframe
C e animations enable
e you to specify a set of property vaalues to applyy to a target e
element at
d
distinct steps in the animattion. You exprress the steps as percentagees of the elap
psed time for tthe
a
animation. Yo
ou can start an
nimations pro ogrammatically and handle events that o occur as the an nimation
p
progresses.
T
Test Your Kno
owledge
Question
Rotaate
Tran
nslate
Anim
mate
12-40 Animating the User Interface
Question
Scale
Skew
Module 13
Implementing Real-time Communication by Using Web
Sockets
Contents:
Module Overview 13-2
Modu
ule Ove
erview
We eb pages requ uest data on ddemand from a web serverr by submitting HTTP reque ests. This moddel is ideal
forr building inte
eractive appliccations, where
e the functionnality is driven
n by the actionns of a user. H
However, in
an application that needs to display consta antly changing information n, this mechannism is less suitable. For
exaample, a finan ess if it shows prices that arre even a few minutes old, aand you
ncial stocks paage is worthle
cannot expect a user to be prrepared to co onstantly refreesh the page d displayed in th
he browser. Th his is where
weeb sockets are e useful. The W
Web Sockets A API provides a mechanism ffor implemen nting real-time e, two-way
communication between web b server and bbrowser.
This module introduces web sockets, descrribing how they work, and explaining hoow to create a web
soccket connection that can b
be used to tran
nsmit data in real time betw
ween a web p
page and a weeb server.
Ob
bjectives
e, you will be able to:
Aftter completing this module
• Use the We
eb Sockets API to connect tto a web serve
er from a web
b page, and exxchange messsages
between the web page and
a the web server.
Programming in HTTML5 with JavaScrippt and CSS3 13-3
3
Lesson 1
Intro
oduction to W
Web Sockets
The Web Sockkets API enables web pages and web serrvers to exploit the socket p
T protocol. In th
his lesson,
y will learn why the Web
you b Sockets API is a useful add
dition to the communicatio
c ons mechanisms available
f building w
for web applicatio
ons, and what happens whe en a page con eb server by using a web
nnects to a we
s
socket.
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Explain th
he problems tthat web sockkets are intend
ded to solve.
Th
he Problem of Web
b-based Re
eal-time Communi
C cations
• Continuous polling. The e page conne ects to the servver and sendss an AJAX request to the seerver for
new data. T ds, indicating that the data has not chan
The server insttantly respond nged since the e last
request, or sends back thhe new data. TThe page then n closes the co
onnection. Th
his process is rrepeated
every few seeconds.
• Long pollin ng. The page connects to tthe server, setting the conn nection timeouut value to a vvery long
period of time (up to sevveral hours, de
epending on tthe applicatio on), and then sends a reque est to the
server for new data. The server only reeplies if it has new data to send.
s The con
nnection is clo
osed when
either the timeout periodd is reached oor new data is sent to the p page. The proccess then startts again.
This mechanism has an advantage
a oveer the continu uous polling aapproach in th
hat the overhe ead of
opening an nd closing manny short-livedd network con nnections is re
educed, but th
he cost is the need
n to
maintain ann open netwo ork channel to the server. Th he server mayy only be able
e to support a limited
number of concurrent ne etwork conne ections, and a web page maay not be able e to connect tto a server
when this limit is reached
d.
Bo
oth of these m well understood, but they sh
methods are w hare a commo
on set of disad
dvantages:
W
What is a Web Sock
ket?
• Web Socckets API, which is a World d Wide Web CConsortium (W W3C) specification that detaails a
JavaScript API enabling g web pages to ockets. It is not part of the W
t use web so W3C HTML5 sstandard, but
it is part o
of the wider faamily of HTM
ML5 standards defined by thhe Web Hyperrtext Application
Technolo ogy Working Group
G (WHATTWG).
The Web Sockkets API is onlly a draft stan
T ndard at this tiime, but mostt modern brow
wsers supportt it. Internet
E
Explorer 10 is the first version of Internet Explorer to ssupport web ssockets.
H
How Do Web Socketss Work?
The web sockkets protocol d
T defined in RFC hanging data between a
C6455 states tthere are fourr steps to exch
c
client and a se
erver:
1
1. The clientt requests a co
onnection to the server ove
er HTTP or HT
TTPS.
2
2. If the servver responds positively, botth the client and
a server swiitch to the we eb sockets pro
otocol (known n
as WS) orr WSS (the seccure variant of WS), and a p persistent bi-d
directional soccket connectio
on is created
between the two.
3
3. The clientt and server send and receiive messages over the open connection.. The format o of the data in
the messaages is entirely up to the cllient and serve
er; the client just
j needs to cconstruct messsages in a
format th
hat the server expects, and vice versa.
4
4. The clientt or the server explicitly clo
oses the conne
ection, or a tim
meout value is reached.
Lesson 2
Using
g the W
WebSoccket AP
PI
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to write JavaScript co
ode in a web p
page that:
• Sends me
essages to a se
erver by using
g a web socke
et.
• Receives messages from
m a server byy using a web socket.
13-8 Implementing Real-time Coommunication by Using Web Sockets
Co
onnecting
g to a Serv
ver by Using a Web
b Socket
The WebSocket API defines the WebSocket object for e establishing a connection b between a clieent
ap
pplication and a server. The WebSocket object provid des the metho ods that a clien
nt object usess to connect
to a server, and to send and receive
r messa
ages. The Web bSocket object also contains a number of
pro
operties that maintain information abouut the state off the current connection.
c
The WebSocket object is alsoo available as the WebSoccket property of the windoow object. Youu can
de
etect whether the browser rrunning a webb page suppo
orts web sockeets by using th
he following code:
c
if (windoow.WebSocket
t) {
alert(""WebSocket is supported");
} else {
alert(""WebSocket is not supported");
}
Op
pening a Co
onnection
The start of all ccommunicatio on with a web
b socket serverr is the openin
ng handshakee over HTTP bbetween the
clie
ent code runn ning in a web page and the
e server. The WWebSocket constructor en nables you to create a
neew connection This URL uses the ws or wsss scheme to
n and to specify the URL of the server to connect to. T
dicate that it is a web socke
ind et address:
var socke
et = new Web
bSocket('ws:/
//websockets
server.conto
oso.com/bookings');
var socke
et = new Web
bSocket("ws:/
//localhost:
:55981/live/
/socket.ashx");
If yyou need to e
establish an en
ncrypted conn
nection, you can
c use the se
ecure web sockets protocol wss://.
This protocol usses port 443 bby default.
var socke
et = new Web
bSocket('wss://secure.we
ebsocketserv
ver.contoso.com/bookings
s');
The WebSocket API is asynchronous. This is because it can take time to establish a connection, and after a
connection has been opened, messages can be received at any time over that connection. After you have
created a WebSocket object, you should not attempt to use it until it is ready. You can determine the
state of the WebSocket object by examining the readyState property. This property can have the
following values:
• CONNECTING (0), which indicates that a WebSocket object has been created, but a connection is
still being made between page and server.
• OPEN (1), which indicates that a connection between page and server has been established.
• CLOSING (2), which indicates that the closing handshake is in progress.
• CLOSED (3), which indicates that the connection between page and server has been closed or could
not be established.
You can also detect when a connection has been opened successfully by handling the open event of the
WebSocket object. At this point, you can start to send and receive messages over the connection.
socket.onopen = function() {
// Web Socket Server is connected
alert("Connection to server now open!");
//send message etc ...
};
Note: You can also choose to use the addEventListener() method to bind to the events
fired by the WebSocket object, like this:
function sendMessage() {
// Create a message and send it to the server
...
};
socket.addEventListener("open", sendMessage);
If an error occurs while connecting to the server, the error event fires (this event also fires if an error
occurs while disconnecting from, or sending a message to, the server). The error message is available as
the data property of the event object. You can bind to this event by using the onerror callback.
socket.onerror = function(event) {
// An error has occurred
alert("An error has occurred: " + event.data);
};
Closing a Connection
To close the connection to the server, call the close() function of the WebSocket object. This function
takes two optional parameters, code and reason, which enable you send the server an exit status code
(described in RFC6455) and a text-based reason for closing the connection.
socket.close();
socket.close(1000, "No Error. All communication finished with.");
The close event fires when a connection has been closed. The event object has three properties:
• wasClean, which is a Boolean value indicating whether the connection was closed cleanly (true) or
experienced a problem (false).
• code, which is the exit status code (laid out in RFC6455) indicating why the connection was closed.
13-10 Implementing Real-time Communication by Using Web Sockets
• reason, which is a text string giving a reason why the connection was closed.
The following code shows an example that detects whether a connection was closed successfully or not:
socket.onclose = function(event) {
// Connection has been closed
if (event.wasClean) {
alert("Connection closed OK");
} else {
alert("Connection closed with issues. Code " + event.code);
}
};
P
Programming in HTM
ML5 with JavaScript and CSS3 13-11
1
S
Sending M
Messages to a Web Socket
var mes
ssage = ...; // Message to be sent
socket.send(message);
M
Message dataa can be sent as
a one of fourr object typess:
functio
on sendRequest(socket, t
text) {
sock
ket.send(JSON.stringify(
({ request : text }));
}
functio
on sendFile(socket) {
var file = document.querySe
elector('inp
put[type="file"]').files
s[0];
sock
ket.send(file);
}
13-12 Implementing Real-time Communication by Using Web Sockets
• An ArrayBuffer object. This object represents a buffer used to store raw binary data. The data can
then only be accessed by using a typed array view such as Uint8Array and Int32Array. The following
example sends an array of integers:
function sendRawData(socket) {
var numbers = new Uint8Array([8,6,7,5,3,0,9]);
socket.send(numbers.buffer);
}
• An ArrayBufferView object. This object represents a typed array view that can be used to access
binary data in an ArrayBuffer. The following example sends the data from an image displayed by
using a canvas:
After you have sent a message, you can see whether it was transmitted successfully by checking if
bufferedAmount property of the WebSocket object is zero.
P
Programming in HTM
ML5 with JavaScript and CSS3 13-13
3
R
Receiving Message
es From a Web
W Sock
ket
The WebSockket protocol iss bidirectional, and the servver that you are connected to may send you a
T
m
message at anny time. The message
m even
nt fires when a message is received
r from
m the server giiving you the
o
opportunity to
o receive and process the mmessage. The event object passed to the e message evvent handler
h two prope
has erties:
socket.onmessage = function(evvent) {
// Message
M has been receiveed
if (event.type
( == "Text") {
h
handleTextMe ssage(event.data);
} else {
h
handleBinary Message(sock
ket.binaryTy
ype, event.data);
}
};
functio
on handleTextMessage(tex
xt) {
var message
m = JSON.parse(tex
xt);
if (m
message.request) { // do
o something }
}
Lab: Perform
ming Real-tim
me Communica
ation by
y Using
g Web
kets
Sock
S
Scenario
During conferrence sessionss, attendees m
D may wish to assk questions. D
Distributing m
microphones aamong
m
members of the audience ccan be probleematic and slo
ow, so you havve been asked d to add a pag
ge to the
w
website that e
enables attenddees to submit questions. SSpeakers can either
e respond
d immediatelyy or later,
d
depending onn the nature o
of the questions and the sesssion.
Note: T
The web socke et server is implemented byy using ASP.NET and C#. Th
he details of how
h
t server wo
this orks are outsid
de the scope o of this lab.
O
Objectives
A
After completting this lab, you
y will be able to:
• Create a w
web socket th
hat connects tto a server and
d receives me
essages.
• Serialize aand send messsages to a we
eb socket.
• Send and
d receive different types of messages by using a web ssocket.
E
Estimated Tim
me: 90 minutes
• Virtual Machines: 2048
80A-SEA-DEV1
11-13, MSL-TMG1
13-16 Implementing Real-time Communication by Using Web Sockets
• Password: Pa$$w0rd
Programming in HTML5 with JavaScript and CSS3 13-17
3. Start Visual Studio and open the ContosoConf.sln solution from the E:\Labfiles\Starter\Exercise 1
folder.
4. Start the application and view the Live page. Ignore the error that occurs (this error happens because
the JavaScript code for the page is not yet complete). Using this page, an attendee can type a
question and click Ask to send it to the presenter. All questions asked by all attendees will appear on
this page, underneath the Ask a question box.
13-18 Implem
menting Real-time CCommunication by Using Web Sockets
7. Review the HTML markup for this pag ge and note th he <form> ellement used tto ask questio
ons,
together wiith the emptyy <ul> elemen
nt that will dissplay question
ns.
8. Also, note tthe <script> element referrencing the liv
ve.js file in the /scripts/pa
ages folder.
9. Open the liive.js file that is in the /scripts/pages fo older and review the code. The JavaScrip
pt code in
ge object, wh
this file defiines a LivePag hich controls tthe page. The code to manipulate the usser
interface annd respond to o DOM eventss has already b been written.
X Task 2: Re
eceive messsages by usiing a web so
ocket
1. In the live.jjs file near the
e end of the file (just before
e the call to th
he create me
ethod), create a new
WebSocket object that cconnects to th he socket servver at localho e/socket.ashx.
ost:55981/live
2. alizeSocket m
In the initia method, assign
n a callback fu
unction to the
e onmessage property of tthe socket.
oke the handlleSocketMesssage method. Ensure that tthe correct vaalue of this
This callbacck should invo
is maintaineed when callin
ng handleSoccketMessage e.
Note: You
u will impleme
ent the code ffor the handleSocketMesssage method in the next
ste
ep.
Programming in HTML5 with JavaScript and CSS3 13-19
• If the message contains a questions property, then call then the handleQuestionsMessage method.
2. Review the displayQuestion method. This method adds the questions specified as the parameter to
the list below the Ask a question box on the page.
• What are some good resources for getting started with HTML5?
• Can you explain more about the Web Socket API, please?
• This is an #&!%!* inappropriate message!!
Results: After completing this exercise, you will have added JavaScript code to the Live web page to
receive questions from a web socket and to display them.
13-20 Implementing Real-time Communication by Using Web Sockets
2. Open the live.js file in the scripts/pages folder. In this file, the LivePage object has methods that
handle the Ask a question form submission. The question text is passed to the askQuestion method.
3. In the askQuestion method, create a variable named message that contains an object with the
following format (this is the message structure expected by the socket server):
{ ask: text }
2. Open a second tab in Internet Explorer and view the Live page again.
3. Use the Ask a question form to submit questions.
4. Verify that the questions are displayed on the pages in both tabs.
Note: The message This is an #&!%!* inappropriate message might disappear from the
second tab.
Results: After completing this exercise, you will have modified the Live question page to enable users to
ask questions by sending messages to the server by using the web socket.
Programming in HTML5 with JavaScript and CSS3 13-21
2. Open the live.js file in the scripts/pages folder, and review the createReportLink method. This
method creates a new link element and adds attributes that cause it to be rendered appropriately.
//item.appendChild(this.createReportLink());
{ report: questionId }
3. Test that clicking a Report link removes the question (there will be a short delay while the question is
assessed).
Results: After completing this exercise, you will have added a feature to the Live page that enables users
to report inappropriate questions and causes the application to remove them.
13-22 Implem
menting Real-time CCommunication by Using Web Sockets
Modu
ule Reviiew and
d Takea
aways
M
Module Revie
ew
In this module, yyou have learrned how web b sockets provvide a fast, rob
bust and efficient solution ffor real-
tim
me communiccation between a web page er. You have also learned ho
e and its serve ow to connect to a web
soccket from a cllient application by using the WebSocke et API, and hoow to send and d receive messsages over
awweb socket.
erify the correcctness of the statement by placing a maark in the column to the rig
Ve ght.
S
Statement Answer
Q
Question
H
How does a cllient create a connection tto a web sock
ket server?
S
Select the corrrect answer.
Web sockets
s use a stateless
s proto
ocol similar to
o HTTP. A client application
n simply
specifiies the addresss of the serve
er as a parameeter of the sen
nd() function of the
WebSo ocket object. A connection is automatica ally establishe
ed while the m
message is
sent and then close ed.
Question
The client has to wait until the server responds to send a message that grants it
permission to connect.
14-1
Module 14
Performing Background Processing by Using Web Workers
Contents:
Module Overview 14-2
Modu
ule Ove
erview
Ob
bjectives
Aftter completing this module
e, you will be able to:
Lesson 1
Unde
erstand
ding We
eb Worrkers
Lesson
n Objectives
After com
mpleting this llesson, you wiill be able to:
• Describe the purpose o of web workers.
• List some
e common sce
enarios for using web worke
ers.
• Explain ho
ow web workkers run in an isolated envirronment.
W
What is a W
Web Work
ker?
JavvaScript code running in a browser is exe ecuted by using a single th hread. What thhis means is thhat while
thee browser is ru
unning your JJavaScript cod de it cannot do anything else, such as resspond to the user
cliccking a button on a form o on a web page e displayed byy the browserr, or even dispplay text that the
t user
miight be typingg. This is not a problem in mmany cases: The JavaScript used by a we eb page usually consists
of a number of discrete functtions, each of which runs quickly in respo onse to an evvent, and the uuser does
noot notice the minor
m delay inn response wh hile the code is running. Ho owever, if you write JavaScrript code
thaat has to perfo
orm more com mplex or reso ource-intensive t browser can become noticeably
e tasks, then the
lesss responsive, or even appe ear to stop alto
ogether. In th
his situation, u
users frequenttly assume thaat the
appplication has crashed. Theyy may try and close the bro owser before ttrying a task aagain—and ge etting the
samme frustratingg result.
A web
w worker enables you to o offload long-running and data-intensivve tasks to a separate
s execu ution
environment, diistinct from th
hat of the web
b page, leaving the browser free to hand dle the user in
nterface.
This keeps the web
w page resp ponsive to the
e user while th
he web worke
er performs th he data processsing
be
ehind the scennes.
A web
w worker iss a piece of JavaScript codee that runs in parallel to the
e web page. Itt is initiated by
b code
nning in a web page, but h
run has no access tto any resources on that pa age. Instead, the
t code in th he web
page communiccates with thee web worker by sending it messages con ntaining the d
data that the web
w worker
ne
eeds. The web worker can reespond by sending messag ges back to th he code in thee web page. Th he code in
e web page has full control over the web
the b worker, and d can terminatte it at any tim
me.
Note: Bro
owser vendorss are free to im
mplement web b workers in w
whatever way is most
ap
ppropriate for the platform on which the e browser is ru
unning. Internet Explorer usses threads,
wh wsers may acttually create ccompletely separate host processes. If th
hile other brow hey are
Programming in HTML5 with JavaScript and CSS3 14-5
available, some implementations make use of multiple processor cores to implement true
multiprocessing.
Additional Reading: For information about the web worker specification, visit
http://go.microsoft.com/fwlink/?LinkID=267757.
14-6 Perform
ming Background Proocessing by Using W
Web Workers
We
eb workers arre ideally suite
ed to a varietyy of scenarios,, including:
• Performing long-running g or slow I/O operations. A web worker ccould be used d to send dataa to a web
service and await a respoonse, while the web page continues runn ning. Alternatively, a web w
worker
could use th
he File API to read data fro
om the local file system for processing, and then uploaad this data
to a web se
ervice or pass it to the web page for disp
play.
• Dividing woork between cconcurrent thrreads. Operattions that invo olve processing a large amo ount of
data, such aas the informaation held in a large array o
or a file on dissk, could be d
delegated to a collection
of concurreent web worke ers. A master wweb-worker initiated by the web page can c act as a coontroller
that createss subordinate web workers and delegate es work to theem. The maste er web workerr
aggregates the results annd sends them m back to the web page. If the computerr running the browser
has a proceessor with mulltiple cores, an
nd depending g on how the browser implements web w workers,
this model provides a go ood way to exploit the para allel processing capabilities of the processsor.
Programming in HTTML5 with JavaScrippt and CSS3 14-7
7
W Worrker Isolation
Web
A web workerr runs in isolattion from the web page and from any otther web workers that the page creates.
Given that a w
G web worker ha as no access tto the data on
n a web page, when a web page creates a new web
w
worker it musst provide it w mation that it needs by passing messages. The web paage can use
with the inform
t postMesssage() functio
the on to send a mmessage, and it can catch m messages sent back from thhe web workerr
b handling the message e
by event. The weeb worker ope erates in a sim
milar manner, receiving
r messsages by
h
handing the m
message even nt and sending replies by uusing the posttMessage() fu unction.
14-8 Perform
ming Background Proocessing by Using W
Web Workers
Dedicated and
a Share
ed Web W
Workers
A dedicated
d woorker is the excclusive properrty of the pag
ge that created
d it. It runs asyynchronouslyy from the
page, but can b be controlled b by the page. OOnly the pagee that created the worker can post messaages to it
and receive messsages back frrom it. A dedicated web wo orker can be tterminated byy the page thaat created
it. Note that if the web page is closed (if th he browser terminates, or tthe user navig gates to a diffe
erent page),
theen any dedicaated web workkers created b by that page w
will stop. A we
eb worker can n also forcibly terminate
itseelf. A dedicate
ed worker is iddeal for perfoorming a long-running taskk on behalf off a web page, such as
upploading a larg ge file or proccessing a large
e amount of ddata.
A shared
s worker is created byy one page, bbut other pagees running as part of the sa
ame web appllication can
poost messages tto, and receive
e messages frrom, the samee shared workker. Shared wo orkers can be controlled
byy any page in tthe web appliication. Shared workers sto navigates to a different website.
op if the user n
A shared
s worker provides a mmechanism for implementin ng centralized
d application processes, andd can also
e used to implement cross-page communication. For example,
be e a shopping cart on
o a catalog site could
be
e implemented d by using a shared
s workerr that uses AJA
AX methods to quietly dow wnload and shhare very
de
etailed producct informationn for items in the
t cart. All thhe catalog pag user launches have access
ges that the u
to this shared w
worker, keepin
ng the cart in easy
e reach and scope no m matter how maany pages the e user
op
pens while cassually browsing the store, in
ncluding clicking the back button
b in the browser.
Programming in HTTML5 with JavaScrippt and CSS3 14-9
9
Lesson 2
Perfo
orming Asynch
hronou
us Proce
essing b
by Usin
ng Web
b
Workkers
HTML5 provid
H des a JavaScript API for creating and managing web w
workers. In thiis lesson, you will learn
h
how to createe web workerss, communicate with them, and handle eerrors that maay occur while e a web
w
worker is runn
ning.
L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:
• Create an
nd terminate a dedicated web
w worker.
• Send messsages to a we
eb worker, and receive messsages from a dedicated we
eb worker.
• Explain ho
ow to implem
ment the structure of a web
b worker.
• Explain ho
ow to create a shared web worker.
14-10 Perforrming Background PProcessing by Using Web Workers
Crreating an
nd Termin
nating a Dedicated W
Web Worrker
To
o create a dedicated web worker, you firsst create a new w Worker obj bject. The Worrker constructtor expects
the
e URL of a JavvaScript file ass a parameterr. This JavaScriipt file contain
ns the code th
hat the web wworker runs.
The following coode example checks that th he browser su upports web w workers, and then creates a new web
woorker that runs the JavaScript code in the e processScrip
pt.js file:
var webWo
orker;
if( typeo
of(Worker)!=
== "undefined") {
webWo
orker = new Worker("processScript.j
js");
}
It iis important to understand that the URLL of the script is a web-hostted file that m
must be part of the same
weeb application n as the HTMLL5 page running the script; you cannot u use this mechaanism to run JavaScript
J
code that is locaated at a diffe
erent site.
We
eb workers teerminate automatically wheen the contain ning page is closed, and the
e resources ussed by the
we
eb worker are released. Howwever, the we
eb page that ccreates a dedicated web wo orker can end the web
wo
orker at any time by using the
t terminate e() function:
webWorker
r.Terminate(
();
We
eb workers may also termin
nate themselvves:
self.clos
se();
Yo
ou can also cre
eate inline web workers. Thhe JavaScript ccode for an in
nline web workker is defined as part of
the
e web page th er than being held in a sepaarate JavaScrip
hat starts the worker, rathe pt file. This en
nables your
Programming in HTML5 with JavaScript and CSS3 14-11
code to be more self-contained, and reduces the number of code files that you need to track and
maintain in a complex application.
You can create an inline web worker in several different ways. The following code example creates a Blob
containing the JavaScript code for the web worker, and then uses the createObjectURL() function of the
URL object to create a URL that references this object. The code passes this URL to the Worker
constructor.
var workerBlob = new Blob(["{ /* Code for web worker goes here */ }"]);
var workerURL = URL.createObjectURL(workerBlob);
var webWorker = new Worker(workerURL);
...
Another technique is to define the code for the web worker in a <script> element, as shown in the
following example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
...
<script id="web-worker" type="javascript/worker">
// Code for web worker goes here
</script>
<script type="text/javascript">
...
var workerBlob = new Blob([document.querySelector('#web-worker').textContent]);
var workerURL = URL.createObjectURL(workerBlob);
var webWorker = new Worker(workerURL);
...
</script>
</body>
</html>
The code for the web worker has the type javascript/worker. The JavaScript engine in the browser will
not recognize this type, so it will not attempt to parse and run the code, but will instead treat it as a block
of data (you could use almost any convenient string for the type). The JavaScript code for this page
creates a Blob object that references this script, and then creates a URL for this object, which in turn is
used to create a Worker object.
Note: Inline web workers are not widely supported, and they are not currently supported
by Internet Explorer.
Additional Reading: For more information about implementing web workers with Internet
Explorer 10, visit http://go.microsoft.com/fwlink/?LinkID=267759.
14-12 Perforrming Background PProcessing by Using Web Workers
Co
ommunicaating With A Dediccated Web
b Worker
// proces
ssScript.js
function messageHanddler(event) {
self.po
ostMessage(""Received: " + event.dat
ta);
}
self.addE
EventListeneer("message", messageHan
ndler, false
e);
function replyHandle
er(event) {
alert("
"Reply: " + event.data); // Display
y the reply in an alert
}
var webWo
orker;
...
webWorker
r = new Work
ker("processScript.js");
; // The web
b worker code is in this
s file
webWorker
r.addEventListener("message", reply
yHandler, fa
alse);
webWorker
r.postMessag
ge("Here is some data");
;
...
Programming in HTML5 with JavaScript and CSS3 14-13
If an exception occurs while the web worker is running, it will raise the error event and then terminate.
The web page should be prepared to catch this event. The following code shows an example:
function errorHandler(event) {
console.log(event.message);
}
...
webWorker.addEventListener("error", errorHandler, false);
...
The event object passed to the error handler contains the following properties:
o filename. The name of the script file in which the error occurred.
o lineno. The line number of the script file where the error occurred.
14-14 Perforrming Background PProcessing by Using Web Workers
Th
he Structu
ure of a W
Web Worke
er
A typical
t web w
worker uses the e message evvent to receive messages, and
a then perfo orms processiing based
on
n the data in the message b before waiting
g for the next message. A co ommon idiom m is to implem
ment the
Co
ommand patte ern, in which e
each messagee contains a field that indicates the actio
on that the we
eb worker
ould perform. Other fields can contain the informatio
sho on that the we eb worker sho ould process b
by
pe
erforming the action:
function messageHand
dler(event) {
var d
data = event
t.data;
switc
ch (data.com
mmand) {
case "DOWORK": /
// process the DOWORK co
ommand
.
...
b
break;
case "DOMOREWORK
K": // process the DOMOR
REWORK comma
and
.
...
b
break;
case "FINISH": /
// tidy up and shut down
n
...
self.
.postMessage
e("Shutting down");
self.
.close();
}
Re
emember that a web worke er is itself single-threaded, sso if the proce
essing that it performs
p in re
esponse to
ammessage takess a lengthy peeriod of time, it will not be able respond to other messsages immed diately; the
meessages will bee queued andd handled whe en processing g completes. In these situations, the web worker
could itself dele
egate work to other web wo orkers that it ccreates and manages,
m leaviing it free to h
handle
meessages as theey arrive.
A web
w worker m may require acccess to functions and utilitties defined in
n other JavaSccript files. For example, a
eb worker mayy use the jQuery library to send requestss to an extern
we nal web servicee. A web workker does
no
ot have a DOM
M, so you cann not reference scripts by using <script> elements. Insttead, a web w worker can
use
e the importS
Scripts() funcction, as show
wn in the follow
wing example e:
importScr
ripts("maths
s.js");
Note: You
u can add multiple JavaScriipt files by usiing the imporrtScripts() function.
Programming in HTML5 with JavaScript and CSS3 14-15
It is common to use the importScripts() function near the start of the web worker code to ensure that
the objects and functions defined by these scripts are in scope.
Web workers have access to the Global object that defines a set of global functions, in much the same
way that a web page does. However, the Global object for a web worker is scoped to that web worker,
and it does not contain any of the data items or functions defined by the web page. However, this does
mean that many of the built-in JavaScript global functions are available to web workers.
Web workers have access to the navigator object. This object contains information that the web worker
can use identify the browser, including appName, appVersion, platform, and userAgent. Web workers
also have read-only access to the location object, which provides information about the URL of the
current page.
14-16 Perforrming Background PProcessing by Using Web Workers
Crreating a S
Shared Web
W Worke
er
A dedicated
d web worker is acccessible only from the pag ed it. To creatte a web workker that is
ge that declare
acccessible from all pages in a web applicattion, you can create a share
ed web worke er.
Yo
ou create a shaared web worrker by using tthe SharedW Worker constru uctor. Howeve er, to enable multiple
m
pages to send m messages to th
he web worke er, each page has its own po ort that it uses. A web page e sends
me essages to the
e web worker through its pport by using tthe postMesssage() functio on. Any repliess are
recceived by usin
ng the messag ge event on tthe same portt. The followin ng code example shows how w to create
a sshared web worker to send and receive m messages. No otice that a we eb page must use the startt() function
of the port befoore sending th
he first messagge. This functiion alerts the web worker tthat a new con nnection is
be
eing establisheed and enablees it to preparre to receive messages
m on tthis port:
function replyHandle
er(event) {
...
}
var share
edWebWorker;
...
sharedWeb
bWorker = ne
ew SharedWorker("sharedP
ProcessScrip
pt.js");
sharedWeb
bWorker.port
t.addEventListener("mess
sage", reply
yHandler, false);
sharedWeb
bWorker.port
t.start();
...
var data = ...;
sharedWeb
bWorker.port
t.postMessage(data);
A shared
s web w worker has a co
onnect eventt that fires eacch time a web
b page opens a new port byy using the
sta
art() function. This event re mation about tthe port that has been ope
eceives inform ened, and the handler
typ
pically uses th
his information
n to add a meessage event handler to the port, and th
hen start the p
port, so that
the
e web workerr can receive messages
m on it. The code below shows an example:
function messageHand
dler(event) {
// Hand
dle messages
s received on a port
...
}
function connectHand
dler(event) {
var por
rt = event.p
ports[0];
port.ad
ddEventListe
ener("message" messageHa
andler, fals
se);
port.st
tart();
}
self.addE
EventListene
er("connect", connectHan
ndler, false
e);
Programming in HTML5 with JavaScript and CSS3 14-17
A shared web worker sends a reply back to a web page by using the postMessage() function of the port
that the web page opened. At the present time, the shared web worker event-handling mechanism does
not provide any built-in way to identify which port belongs to which web page, so the web worker must
track this information itself. One technique is for a web page to include an identifier in each message that
it sends, and for the web worker to associate each identifier with the corresponding port.
Best Practice: It is worth noting that shared web workers have not been widely taken up
because of security considerations. Internet Explorer does not currently support them.
14-18 Perforrming Background PProcessing by Using Web Workers
Lab: C
Creating
g a Web
b Work
ker Proccess
Sccenario
Whhen a speakerr creates a con
nference badg ge, the speake
er drags and ddrops an imagge containing
ga
ph
hotograph ontto the web pa age. This phottograph may beb a color ima age. Howeverr, the conferen
nce speaker
badges will be p
printed in grayyscale. Thereffore, the web page that cre
eates the badgges should ren
nder the
spe
eaker photograph in grayscale in order tto give an acccurate represeentation of the printed output.
An
n image file m
may be many mmegabytes in size. To avoidd uploading laarge files to a server for pro
ocessing,
you have decideed to convert the photos to
o grayscale byy using JavaSccript code runnning in the web
w
bro
owser.
The conversion process may take some tim me, so the web d provide the user with a progress bar
b page should
to indicate how the conversio
on process is progressing.
p
Ob
bjectives
Aftter completing this lab, you
u will be able to:
• eb worker and
Create a we d implement a web worker script.
• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 14-19
First, you will review the HTML markup and JavaScript code for the Speaker Badge page. You will then
update the code so that it converts the speaker photo to grayscale. Next, you will run the application and
verify that the browser becomes unresponsive while processing a large image. You will then create a web
worker and move the CPU-intensive image processing code into the script for the web worker. You will
use messages to communicate with the worker. Finally, you will run the application, view the Speaker
Badge page, and verify that the web browser remains responsive while the image is being processed.
2. Start the 20480A-SEA-DEV11-14 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
3. Start Visual Studio and open the ContosoConf.sln solution from the E:\Labfiles\Starter\Exercise 1
folder.
4. In the ContosoConf project, review the Speaker Badge page. Note the additional <div
class="busy">. This <div> displays the message Creating badge. Please wait… while an image is
being processed.
5. Also notice the script reference to the grayscale.js JavaScript file in the /scripts folder.
6. Open the grayscale.js JavaScript file in the scripts folder, and review the code. Notice that this file
contains a function named grayscaleImage, which converts an image to grayscale. This function
converts the image one pixel at a time, and can take a long time to convert a large image.
7. Also note that the /scripts folder contains another JavaScript file called grayscale-worker.js, which is
currently empty.
2. In the handleDrop method, add JavaScript code to insert the grayscaleImage function into the
processing pipeline for an image by using the jQuery pipe function.
Note: The pipe function enables you to chain function calls together into a pipeline.
14-20 Performing Background Processing by Using Web Workers
4. Drag the file E:\Labfiles\Resources\mark-hanson-large.jpg from File Explorer and drop it onto the
speaker badge canvas in Internet Explorer.
5. While the image is being processed, try scrolling the page or moving to a different page. Note that
the page is frozen.
Note: Internet Explorer may display the message localhost is not responding due to a
long-running script. If this occurs, allow the script to complete.
Note: You can observe the load that Internet Explorer is under by using Task Manager as
follows:
The virtual machine is configured with two virtual CPUs, and the grayscaleImage function will
keep one of the CPUs fully occupied, resulting in an overall processor utilization of approximately
50%. When the grayscale image appears, the processor utilization will drop close to 0.
• The imageData variable in this function contains the data to be converted to grayscale.
• Pass the imageData variable to the web worker by using the postMessage method.
2. Open the grayscale-worker.js file in the scripts folder and add an event listener for the message
event. Leave the function that handles the event empty (you will write the code for this event handler
in a later task, when you implement the functionality to return data from the web worker).
3. Return to the grayscale.js file. In the grayscaleImage function, before the call to postMessage, add
an event listener called handleMessage for the message event of the web worker
• In the message callback, populate the imageData variable with the value in the data property of the
event parameter.
Programming in HTML5 with JavaScript and CSS3 14-21
{ done: imageData }
2. In the grayscale.js file, near the end of the grayscaleImage function, find the following lines of code
that update a temporary canvas with the processed image data and then resolve the deferred object:
3. Move this block of code into the message event callback function (referenced by the
handleMessage variable).
• Retrieve the image data from the data.done property of the event parameter in the callback
function.
Note: You may need to clear the browser cache and restart Internet Explorer before
testing changes to the worker script. To do this, press F12 to show the F12 Developer Tools
window, and on the Cache menu click Clear browser cache.
Results: After completing this exercise, you will have a created a web page that remains responsive while
slow image processing code runs in a web worker.
14-22 Performing Background Processing by Using Web Workers
First, you will add a progress bar element to the web page. Then you will modify the JavaScript code for
the Speaker Badge page to update the progress bar. Next, you will add code to send progress messages
from the web worker. You will receive these messages in the JavaScript code for the Speaker Badge page
and update the progress bar. Finally, you will run the application, view the Speaker Badge page, and
verify that the progress bar is displayed and updated while a photograph is being converted.
2. In the speaker-badge.htm file, add a progress bar to the busy <div> element. This progress bar
should display values ranging from 0 to 100
3. Open the speaker-badge.js file in the scripts/pages folder, and modify the SpeakerBadgePage
object to control the progress bar element:
• In the initialize method, create a variable called progress that references the progress element.
• Add a function named updateProgress to the SpeakerBadgePage object. This function should take
a single parameter and update the value displayed in the progress bar with this parameter.
• In the handleDrop method, update the image processing pipeline and insert a call to the progress
function immediately after initiating the call to the grayscaleImage function.
var previousProgress;
var updateProgress = function (pixels, index) {
var progress = Math.floor(100 * index / pixels.length);
// Avoid flooding the client with the same repeated progress.
if (previousProgress !== progress) {
postMessage({ progress: progress }); previousProgress = progress;
}
};
P
Programming in HTM
ML5 with JavaScript and CSS3 14-23
3
Note: TThe updateProgress function sends prog gress messagees. The amount of progresss is
ccalculated as a percentage of the numbe er of pixels prrocessed in the image compared to the
n
number of pixxels in the imaage (this inforrmation is passsed in as the index and piixels parametters).
A an optimizzation, this fun
As nction only po osts messagess if there has b able progress since
been measura
t last messaage.
the
2
2. In the meessage event callback that performs the image processing, after th he call to the
grayscaleePixel functio
on, call the up
pdateProgresss function with the same parameters
p that are passed
to the gra
ayscalePixel function. In thhis way, as each pixel is pro
ocessed the progress is possted as a
message.
3
3. Before the done messa
age is posted,, post a final p
progress messsage with a p
progress of 10
00.
X Task 3: Receive
R pro
ogress messsages from tthe web wo
orker
1
1. Open the nd in the messsage event caallback function
e grayscale.jss file in the scrripts folder, an
reference
ed by the handleMessage variable, updaate the code tto handle botth the progre ess and done
messagess.
2
2. For the progress messsage, notify th
he deferred o
object by using
g the followin
ng code:
deferred
d.notifyWith
h(this, [message.progres
ss]);
X Task 4: Test
T the app
plication
1
1. Run the aapplication an
nd view the Sp
peaker Badge
e page.
Note: Y
You may need to clear the bbrowser cache
e and restart Internet Explo
orer before
ttesting changes to the worrker script.
2
2. Drag and
d drop the file E:Labfiles\Resources\markk-hanson-large
e.jpg onto the
e canvas.
3
3. Verify thaat the progresss bar appearss while the im
mage is being processed.
p
FIGUR
RE 14.1: PROG
GRESS BAR FO
OR THE SPEA
AKER BADGE
E PAGE
Modu
ule Reviiew and
d Takea
aways
M
Module Revie
ew
In this module, yyou have learrned how to u
use web workeers to implemment parallel p
processing in a web
ap
pplication. A w
web worker runs a piece of JavaScript codde in parallel to the web pa
age; they mayy be
implemented ass separate threads or proce esses. A web p
page commun nicates with a web worker bby sending
and receiving mmessages.
• A shared we
eb worker can
n be accessed
d by any web page
p in the w
web application that created
d it.
erify the correcctness of the statement by placing a maark in the column to the rig
Ve ght.
S
Statement Answer
SShared web w
workers can sh
hare data in th
he DOM of a web
w page, but
d
dedicated web workers can
nnot. True or ffalse?
Question: How
H does a w
web page com
mmunicate witth a web workker?
P
Programming in HTM
ML5 with JavaScript and CSS3 14-25
5
Courrse Evalluation
Y
Your evaluatio
on of this cou
urse will help M
Microsoft und
derstand the q
quality of yourr learning exp
perience.
P
Please work w
with your train
ning provider to access the course evalua
ation form.
2
2. Start the 20480A-SEA
A-DEV11-01 vvirtual machine if it is not already running, and log on
n as Student
with the p
password Pa$
$$w0rd.
Note: Iff necessary, click Switch Usser to display the list of use
ers.
3
3. On the W
Windows 8 Sta
art screen, clicck the Visual S
Studio 2012 tile.
4
4. In Visual Studio, on the
e File menu, p n, and then click Project/Solution.
point to Open
5
5. In the Op
pen Project dialog box, bro
owse to E:\Labfiles\Starter, click Conto
osoConf.sln, aand then clickk
Open.
6
6. On the Debug menu, cclick Start Witthout Debugg
ging.
7
7. In Interne
et Explorer, if the message Intranet settin
ngs are turned
d off by defau
ult appears, click Don’t
show thiss message agaain.
8
8. Verify thaat the Home page
p appearss in Internet Exxplorer.
10
0. Click Play.
e top of the H
11. Scroll to the Home page.
12. Hover the m
mouse over th
he Register Frree icon and vverify that the
e icon rotates and expandss.
13. At the very top of the paage, mouse ovver but do nott click the item
ms in the men
nu bar.
4. Verify that e
14 each item is h
highlighted ass the mouse trraverses the ittem.
The Schedule p
page looks like
e this:
L1-33
FIGUR
RE 1.3: THE SC
CHEDULE PA
AGE
5
5. In the boxx for the sessiion named Moving the W
Web forward w
with HTML5, click the star icon.
6
6. Verify thaat the star turn
ns yellow, and
d that the num
mber of intere
ested attendee
es increases b
by 1.
7
7. Click the star icon agaiin.
8
8. Verify thaat the star turn
ns white, and that the num es decreases by 1.
mber of interessted attendee
X Task 3: View
V the Re
egister page
e and registter as a new
w attendee
1
1. On the m
menu bar, clickk Register.
2
2. Verify thaat the Registe
er page appeaars.
3. Click Registter and verifyy that all fieldss except Web e highlighted and that the m
bsite/blog are message
This is a re
equired field appears below w the First na
ame field.
9. ose a passwo
In the Choo ord field, type abcd, and th
hen click Regisster.
0. Verify that tthe message You
10 Y must use
e this format: A
At least 5 lette
ers and numb
bers appears b
below the
Choose a password field..
The confirmatio
on page looks like this:
L1-55
FIGUR
RE 1.5: THE RE
EGISTRATION
N CONFIRMA
ATION PAGE
X Task 4: View
V the Lo
ocation page
1
1. On the m
menu bar, clickk Location.
2
2. Verify thaat the Locatio
on page appears.
FIGUR
RE 1.6: THE LO
OCATION PA
AGE
3
3. If the messsage localho
ost wants to ttrack your ph
hysical locatiion appears in
n the Internett Explorer
message bar, click Allo
ow once.
4
4. In the Ena
able Location
n Services dia
alog box, clickk Yes.
L1-6 Programm
ming in HTML5 withh JavaScript and CSSS3
6. Scroll to the
e bottom of the page.
7. Verify that tthe conferencce venue map
p is displayed.
X Task 5: Su
ubmit a que
estion and p
provide con
nference fee
edback
1. On the men
nu bar, click L
Live.
7. On the men
nu bar, click F
Feedback.
8. k page appears.
Verify that tthe Feedback
The Feedback p
page looks likke this:
L1-77
FIGUR
RE 1.8: THE FE
EEDBACK PA
AGE.
9
9. By the firsst question, click the third sstar, and veriffy that the firsst three stars aare highlighte
ed.
1 In the Any additional ccomments boxx, type Good conference, aand then click Send Feedbaack.
12.
Results: Afte
er completing
g this exercise
e, you will be aable to describ
be the feature
es of the Conttoso
Conference web applicatiion and list th
he technologie es that are use
ed to implement them.
L1-8 Programming in HTML5 with JavaScript and CSS3
2. Double-click index.htm.
3. In the index.htm file, at the start of the <body> section, find the <nav> element.
4. Verify that the <nav> section contains the following HTML markup:
<nav class="page-nav">
<div class="container">
<a href="/index.htm" class="active">Home</a>
<a href="/about.htm">About</a>
<a href="/schedule.htm">Schedule</a>
<a href="/register.htm">Register</a>
<a href="/location.htm">Location</a>
<a href="/live.htm">Live</a>
<a href="/feedback.htm">Feedback</a>
</div>
</nav>
5. Find the <section> element with the video class, and verify that this section contains the following
HTML markup:
<section class="video">
<h2>Video from last year</h2>
<video src="http://ak.channel9.msdn.com/ch9/265b/9a76fccd-941e-4285-ad00-
9ea200aa265b/MIX09KEY01_high_ch9.mp4"></video>
<div class="video-controls" style="display: none">
<button class="video-play">Play</button>
<button class="video-pause">Pause</button>
<span class="video-time"></span>
</div>
</section>
6. In the <head> section near the top of the file, find the <link> elements.
<head>
...
<link href="/styles/site.css" rel="stylesheet" type="text/css" />
<link href="/styles/nav.css" rel="stylesheet" type="text/css" />
<link href="/styles/header.css" rel="stylesheet" type="text/css" />
<link href="/styles/footer.css" rel="stylesheet" type="text/css" />
<link href="/styles/pages/index.css" rel="stylesheet" type="text/css" />
<link href="/styles/mobile.css" rel="stylesheet" type="text/css" />
<link href="/styles/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
12. Verify that the <nav> section contains the following HTML markup:
<nav class="page-nav">
<div class="container">
<a href="/index.htm">Home</a>
<a href="/about.htm" class="active">About</a>
<a href="/schedule.htm">Schedule</a>
<a href="/register.htm">Register</a>
<a href="/location.htm">Location</a>
<a href="/live.htm">Live</a>
<a href="/feedback.htm">Feedback</a>
</div>
</nav>
13. In the <head> section near the top of the file, find the <link> elements.
14. Verify that the <head> section includes the following link:
<head>
...
<link href="/styles/pages/about.css" rel="stylesheet" type="text/css" />
...
</head>
16. In the schedule.htm file, find the <section class="page-section schedule"> element.
17. Verify that this element contains the following HTML markup:
18. Verify that the schedule.htm file contains the <script src="/scripts/pages/schedule.js"
type="text/javascript"> element near the end.
20. In the register.htm file, find the <section class="page-section register"> element.
21. Verify that this element contains the following HTML markup:
23. Verify that the location.htm file contains the <script src="/scripts/pages/location.js"
type="text/javascript"> element near the end.
25. Verify that this element contains the following HTML markup:
<section class="travel">
<h1>Travelling to ContosoConf</h1>
<h2 id="distance"></h2>
...
</section>
27. Verify that this element contains the following HTML markup:
<section class="venue">
<h1>Interactive conference venue map</h1>
<div id="venue-map">
<svg viewBox="-1 -1 302 102" width="100%" height="230">
<!-- Room A -->
<g id="room-a" class="room">
<rect fill="#fff" x="0" y="0" width="100" height="100"/>
<text x="13" y="55" font-weight="bold" font-size="20">ROOM A</text>
</g>
<!-- Room B -->
<g id="room-b" class="room">
<rect fill="#fff" x="200" y="0" width="100" height="100"/>
<text x="213" y="55" font-weight="bold" font-size="20">ROOM B</text>
</g>
<!-- The outline of the building -->
<polyline fill="none" stroke="#000" points="135,95 140,100 0,100 0,0 100,0
100,80 130,80 130,70 110,70 110,30 190,30 190,70 170,70 170,80 200,80 200,0 300,0
300,100 160,100 165,95"/>
<text x="150" y="55" font-size="12" style="text-anchor:
middle">Registration</text>
</svg>
...
</div>
</section>
30. Verify that this section contains the following HTML markup:
31. Verify that the live.htm file contains the following <script> element near the end:
35. Verify that the feedback.htm file contains the following <script> elements near the end:
FIGUR
RE 1.11: FILES
S IN THE STYL
LES FOLDER
X Task 3: Run
R the app
plication an
nd make live
e modifications
1
1. In Solutio
on Explorer, do
ouble-click in
ndex.htm.
2
2. On the Debug menu, cclick Start Witthout Debugg
ging.
3
3. Switch to Visual Studio
o 2012.
4
4. In Solutio
on Explorer, fin
nd the following markup o
on the index.h
htm page:
<span
n class="fre
ee">· Free ·</
/span>
5
5. Change the word Free
e to Now, as shown
s below iin bold:
<span
n class="fre
ee">· Now ·</s
span>
6
6. In Solutio
on Explorer, in
n the styles fo
older, double-click nav.css.
7
7. Find the following
f style
e:
nav.p
page-nav {
b
background-c
color: #1d1d1d;
l
line-height: 6rem;
f
font-size: 1.7rem;
1
}
8
8. Change the value of th
he backgroun
nd-color prop
perty to blue, as shown bellow in bold:
nav.p
page-nav {
b
background-c
color: blue;
l
line-height: 6rem;
f
font-size: 1.7rem;
1
}
9
9. On the Fiile menu, clickk Save All.
1 Return to
10. o Internet Explorer and presss F5 on the kkeyboard.
L1-14 Programming in HTML5 with JavaScript and CSS3
11. Verify that the Register button now contains the text Register Now and that the background color of
the menu bar is blue.
Results: After completing this exercise, you will be able to describe how the Contoso Conference
application is structured as a Visual Studio 2012 project.
L2-1
4. On the Windows 8 Start screen click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to New, and then click Project.
6. In the New Project dialog box, in the left pane, under Templates expand the Visual C# node, and
then click the Web node.
2. In the Add New Item – ContosoConf dialog box, click HTML Page.
3. In the Name box, type index.htm.
4. Click Add.
5. Using Notepad, open index.txt file located in the E:\Labfiles\Starter\Exercise 1\Resources folder.
6. In Visual Studio, return to the Design View window displaying the Source view for the index.htm file.
7. Inside the <title> element, add the following text from the header section of the index.txt file:
ContosoConf
8. Inside the <body> element, add the following HTML markup, with the text also from the header
section of the index.txt file:
<header>
<h1>ContosoConf</h1>
<p>A two-track conference on the latest HTML5 developments</p>
</header>
9. After the </header> element and before the </body> element, add the following HTML markup
with the text taken from the content section of the index.txt file:
<section>
<p>
L2-2 Programming in HTML5 with JavaScript and CSS3
10. After the body text that you have just added but before the </body> element, add the following
HTML markup with the text also taken from the content section of the index.txt file:
<section>
<h2>Featuring these excellent speakers</h2>
<ul>
<li>Melissa Kerr</li>
<li>David Alexander</li>
<li>Mark Hanson</li>
<li>April Meyer</li>
</ul>
</section>
11. After the body text that you have just added but before the </body> element, add the following
HTML markup with the text also taken from the content section of the index.txt file:
<section>
<h2>Thanks to our sponsors</h2>
<ul>
<li>Trey Research</li>
<li>Litware, Inc</li>
<li>Fourth Coffee</li>
<li>Graphic Design Institute</li>
<li>Southridge Video</li>
</ul>
</section>
12. After the body text that you have just added but before the </body> element, add the following
HTML markup with the text taken from the footer section of the index.txt file:
<footer>
<p>
Hosted by Contoso
</p>
<address>
Conference Center<br />
3 Somewhere Street<br />
Seattle<br />
WA 98999
</address>
<p>
© 2012 Contoso
</p>
</footer>
3. Drag and drop the images folder onto the ContosoConf project in the Visual Studio Solution Explorer
window.
4. In the Design View window displaying the Source view for the index.htm file, replace the text Melissa
Kerr with the following HTML markup:
5. Replace the text David Alexander with the following HTML markup:
6. Replace the text Mark Hanson with the following HTML markup:
7. Replace the text April Meyer with the following HTML markup:
8. Replace the text Trey Research with the following HTML markup:
9. Replace the text Litware, Inc with the following HTML markup:
10. Replace the text Fourth Coffee with the following HTML markup:
11. Replace the text Graphic Design Institute with the following HTML markup:
12. Replace the text Southridge Video with the following HTML markup:
2. In the Add New Item – ContosoConf dialog box, click HTML Page.
5. Using Notepad, open about.txt file located in the E:\Labfiles\Starter\Exercise 1\Resources folder.
6. In Visual Studio, return to the Design View window displaying the Source view for the about.htm file.
7. Inside the <title> element, add the following text from the header section of the about.txt file:
L2-4 Programming in HTML5 with JavaScript and CSS3
About ContosoConf
8. Inside the <body> element, add the following HTML markup copied from the index.htm page:
<header>
<h1>ContosoConf</h1>
<p>A two-track conference on the latest HTML5 developments</p>
</header>
9. After the </header> element and before the </body> element, add the following HTML markup
with the text taken from the about.txt file:
<article>
<h1>ContosoConf brings web designers and developers together</h1>
<section>
<p>
Since the very first Contoso Conf back in 2009, we've been guided by
three principles:
</p>
<ol>
<li>Community Matters</li>
<li>Never Stop Learning</li>
<li>Have fun!</li>
</ol>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae
enim arcu, vitae aliquet purus.
Aenean rhoncus diam et orci porttitor fringilla. In porta lacus a
turpis pretium placerat. Cras viverra
enim eu nibh pretium ornare. Praesent et adipiscing turpis. Duis mi
risus, ornare at bibendum a,
ullamcorper vel tellus. Nulla in egestas velit. Aenean consequat mi
sed tellus iaculis laoreet. Donec et
odio vel felis commodo porttitor.
</p>
<p>
Aenean id ligula est. Pellentesque ut magna ligula. Donec nunc eros,
tincidunt sit amet sollicitudin
in, semper id mauris. Phasellus odio nulla, molestie ac gravida sed,
dignissim in nisl. Nunc luctus
lobortis massa at dapibus. Aenean turpis nibh, hendrerit nec congue
et, elementum a justo. Aenean sit
amet nulla odio. Cras feugiat porta risus nec pretium.
</p>
<h2>What's It All About?</h2>
<p>
Donec vel sem ut dui vulputate porta. Phasellus imperdiet sapien a
arcu adipiscing vitae adipiscing
elit pharetra. Donec sed ante ut eros mattis bibendum non in erat.
Donec sagittis, massa eu accumsan
eleifend, eros justo cursus justo, id consequat mauris diam id magna.
Vivamus quis tortor massa. Nam ipsum metus,
dapibus ac facilisis sit amet, ullamcorper quis risus. Integer aliquet
eleifend accumsan.
</p>
<blockquote>I had a fantastic time and learnt so much!</blockquote>
<p>
Pellentesque facilisis blandit augue id rhoncus. Sed facilisis varius
lectus, eget commodo purus dapibus
nec. In hac habitasse platea dictumst. Etiam imperdiet facilisis
malesuada. Nunc semper venenatis elit ac
lobortis. Duis lorem lorem, pharetra ut scelerisque nec, consequat sed
risus. Morbi rutrum nisl ut ipsum
consectetur porttitor. Phasellus sed nunc id diam tempus congue in a
leo.
</p>
L2-5
<p>
Proin feugiat, turpis id tempor tempor, lorem libero malesuada.
</p>
</section>
</article>
10. Inside the <body> element, add the following HTML markup copied from the index.htm page:
<footer>
<p>
Hosted by Contoso
</p>
<address>
Conference Center<br />
3 Somewhere Street<br />
Seattle<br />
WA 98343
</address>
<p>
© 2012 Contoso
</p>
</footer>
<nav>
<a href="/index.htm">Home</a>
<a href="/about.htm">About</a>
</nav>
4. In the <body> element, before the <header> element, insert the following HTML markup:
<nav>
<a href="/index.htm">Home</a>
<a href="/about.htm">About</a>
</nav>
3. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
Results: After completing this exercise, you will have built a simple HTML5 web application with a Home
page and an About page.
L2-7
5. In the Add New Item – ContosoConf dialog box, click Style Sheet.
9. After the title but before the </head> element, insert the following HTML markup:
11. After the title but before the </head> element, insert the following HTML markup:
html {
/* font-size 62.5% makes 1rem equal 10px for easy size calculations. */
font-size: 62.5%;
font-family: Calibri, Arial, sans-serif;
background-color: #EAEEFA;
}
body {
margin: 0;
/* Default font-size to about 18px */
font-size: 1.8rem;
}
.container {
padding: 0 1rem;
max-width: 94rem;
/* Horizontally center containers */
margin: 0 auto;
}
nav {
background-color: #1d1d1d;
line-height: 6rem;
font-size: 1.7rem;
}
nav a {
color: #fff;
padding: 1rem;
}
h1 {
font-size: 4rem;
letter-spacing: -1px;
L2-8 Programming in HTML5 with JavaScript and CSS3
5. Replace the contents of the <nav> element with the following HTML markup:
<div class="container">
<a href="/index.htm">Home</a>
<a href="/about.htm">About</a>
</div>
6. After the </nav> element and before the <header> element, insert the following HTML markup:
<div class="container">
7. Before the </body> element, insert the following HTML markup to close the <div> element:
</div>
9. Replace the contents of the <nav> element with the following HTML markup:
<div class="container">
<a href="/index.htm">Home</a>
<a href="/about.htm">About</a>
</div>
10. After the </nav> element and before the <header> element, insert the following HTML markup:
<div class="container">
11. Before the </body> element, insert the following HTML markup to close the <div> element:
</div>
2. In Internet Explorer, verify that the About page matches the styling shown by the image in the
previous task.
3. Move to the Home page, and verify that the styling is consistent with the About page.
Results: After completing this exercise, you will have used CSS rules to style the Home and About pages.
L3-1
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
6. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 1, click ContosoConf.sln, and
then click Open.
7. In Solution Explorer, expand the ContosoConf project node, and then double-click schedule.htm.
8. Review the contents of this file and verify that the schedule page section contains the following
markup:
9. Verify that the file contains the following HTML markup towards the end:
13. Review the contents of this file and verify that the first few lines contain the following code:
var schedule = [
{
"id": "session-1",
"title": "Registration",
"tracks": [1, 2]
},
{
"id": "session-2",
"title": "Moving the Web forward with HTML5",
"tracks": [1, 2]
},
{
L3-2 Programming in HTML5 with JavaScript and CSS3
"id": "session-3",
"title": "Diving in at the deep end with Canvas",
"tracks": [1]
},
{
"id": "session-4",
"title": "New Technologies in Enterprise",
"tracks": [2]
},
...
];
X Task 2: Write code to get the schedule list element on the Schedule page
1. In Solution Explorer, double-click schedule.js.
2. After the line containing the TODO: Task 2 comment, add the following line of JavaScript:
X Task 3: Implement the createSessionElement function that creates the list item for a
session
1. In schedule.js, after the line containing the TODO: Task 3 comment, add the following JavaScript
code:
var li = document.createElement("li");
li.textContent = session.title;
return li;
X Task 4: Implement the displaySchedule function that adds session items to the list
for display
1. In schedule.js, after the line containing the TODO: Task 4 comment, add the following JavaScript
code:
X Task 5: Run the web application and view the Schedule page
1. In Solution Explorer, double-click schedule.htm
3. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
Results: After completing this exercise, you will have added a Schedule page to the ContosoConf
application that displays the details of conference sessions.
L3-3
2. In the Open Project dialog box, browse to E:\Labfiles\Start\Exercise 2, click ContosoConf.sln, and then
click Open.
3. In Solution Explorer, expand the ContosoConf project and then double-click schedule.htm.
<ul id="schedule"></ul>
Show:
<input type="checkbox" id="show-track-1" checked="checked"/><label for="show-
track-1">Track 1</label>
<input type="checkbox" id="show-track-2" checked="checked"/><label for="show-
track-2">Track 2</label>
X Task 2: Write code to get the checkbox elements from the Schedule page
1. In Solution Explorer, expand the scripts folder, expand the pages sub-folder, and then double-click
schedule.js
X Task 4: Update the displaySchedule function to display the sessions for selected
tracks
1. In the schedule.js file, in the displaySchedule function, replace the body of the for loop with the
following JavaScript code:
X Task 5: Run the web application and view the Schedule page
1. In Solution Explorer, double-click schedule.htm.
3. In Internet Explorer, verify that both check boxes are selected and that the complete list of sessions is
displayed.
4. Clear Track 1 and verify that only the sessions for Track 2 appear.
5. Select Track 1, clear Track 2, and verify that only the sessions for Track 1 appear.
Results: After completing this exercise, you will have updated the Schedule page to filter sessions based
on which tracks have been selected.
L4-1
3. Log on to the 20480A-SEA-DEV11-04 virtual machine as Student with the password Pa$$w0rd.
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
7. In Solution Explorer, expand the ContosoConf project, and then double-click register.htm.
8. Find and review the comment that starts with the following text:
9. In the <head> element, verify that the following HTML markup is present:
10. Before the </body> tag near the end of the file, verify that the following HTML markup is present:
2. Add the following HTML markup in place of the code that you deleted in step 1:
<div class="field">
<label for="first-name">First name:</label>
<input type="text" id="first-name" name="FirstName" />
</div>
<div class="field">
<label for="last-name">Last name:</label>
<input type="text" id="last-name" name="LastName" />
L4-2 Programming in HTML5 with JavaScript and CSS3
</div>
<div class="field">
<label for="email-address">Email address:</label>
<input type="email" id="email-address" name="EmailAddress" />
</div>
<div class="field">
<label for="password">Choose a password:</label>
<input type="password" id="password" name="Password" />
</div>
<div class="field">
<label for="confirm-password">Confirm your password:</label>
<input type="password" id="confirm-password" name="ConfirmPassword" />
</div>
<div class="field">
<label for="website">Website/blog:</label>
<input type="url" id="website" name="WebsiteUrl" />
</div>
13. In the page header, click the Register link to return to the Register page.
7. In Internet Explorer, verify that the cursor is placed in the First name box.
8. Verify that the Website/blog box has the placeholder text http://.
9. Close Internet Explorer.
11. Add the required attribute shown below in bold to this line:
21. Click Register, and verify that the Thanks for registering page appears.
22. Close Internet Explorer.
3. Add the pattern and title attributes shown below in bold to this line:
15. Click Register, and verify that the Thanks for registering page appears.
Results: After completing this exercise, you will have modified the attendee registration page to validate
the data entered by attendees.
L4-6 Programming in HTML5 with JavaScript and CSS3
2. In the Open Project dialog box, browse to E:\Labfiles\Start\Exercise 2, click ContosoConf.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, and then double-click schedule.htm.
4. In Solution Explorer, in the ContosoConf project, expand the scripts folder, and then expand the
pages folder.
5. Double-click register.js.
// TODO: Task 1 - Get the password <input> elements from the DOM by ID
X Task 3: Write Code to Display a Custom Error Message if the Passwords Differ
1. In the register.js file, find the comment that starts with the following text:
// TODO: Task 3
if (passwordsMatch) {
// Clear any previous error message.
confirmPasswordInput.setCustomValidity("");
} else {
// Setting this error message will prevent the form from being submitted.
confirmPasswordInput.setCustomValidity("Your passwords don't match. Please
type the same password again.");
}
X Task 4: Add Input Event Listeners to the Inputs to Call the checkPasswords Method
1. In the register.js file, find the comment that starts with the following text:
// TODO: Task 4
11. Verify that the Confirm your password box displays the following error message:
Your passwords don't match. Please type the same password again.
2. Double-click register.css.
/* TODO: Task 5
8. Verify that the First name, Last name, Email address, Choose a password, and Confirm your
password boxes are highlighted with colored backgrounds.
Results: After completing this exercise, you will have modified the registration page to validate
password inputs.
L5-1
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
6. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 1, click ContosoConf.sln, and
then click Open.
7. In Solution Explorer, expand the ContosoConf project, expand the scripts folder, and then expand
the pages folder.
8. Double-click schedule.js.
9. Verify that the first line of the file now contains the following JavaScript code:
10. Verify that the createSessionElement function contains the following code:
function createSessionElement(session) {
var li = document.createElement("li");
li.sessionId = session.id;
var star = document.createElement("a");
star.setAttribute("href", "#");
star.setAttribute("class", "star");
li.appendChild(star);
var title = document.createElement("span");
title.textContent = session.title;
li.appendChild(title);
return li;
}
2. After the last line of this comment, add the following JavaScript code:
function downloadSchedule() {
var request = new XMLHttpRequest();
}
L5-2 Programming in HTML5 with JavaScript and CSS3
3. In the schedule.js file, after the previous statement in the downloadSchedule function, add the
following JavaScript code:
downloadSchedule();
function downloadSchedule() {
var request = new XMLHttpRequest();
request.open("GET", "/schedule/list", true);
request.onreadystatechange = function () {
if (request.readyState === 4) {
try {
var response = JSON.parse(request.responseText);
if (request.status === 200) {
schedule = response.schedule;
displaySchedule();
} else {
alert(response.message);
}
} catch (exception) {
alert("Schedule list not available.");
}
}
};
request.send();
}
3. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
4. Verify that the page displays a list of conference sessions.
8. Change the URL in this statement as shown in bold in the following code:
15. In the downloadSchedule function, change the string /schedule/list?fail back to /schedule/list.
Results: After completing this exercise, you will have modified the code for the Schedule page to
displays the list of sessions retrieved from a web service, and to handle errors that can occur when
communicating with a remote service.
L5-4 Programming in HTML5 with JavaScript and CSS3
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 2, click ContosoConf.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, expand the scripts folder, and then expand
the pages folder.
4. Double-click schedule.js.
6. After the last line of the TODO comment in the body of this function, add the following JavaScript
code:
7. Add the following JavaScript code to the end of the saveStar function:
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var data = "starred=" + isStarred;
request.send(data);
if (isStarred) {
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var response = JSON.parse(request.responseText);
if (response.starCount > 50) {
alert("This session is very popular! Be sure to arrive early to
get a seat.");
}
}
};
}
6. Click the star next to Diving in at the deep end with Canvas.
Results: After completing this exercise, you will have updated the Schedule page to send attendee
selections to a web service, and to display a message when a session is popular.
L5-6 Programming in HTML5 with JavaScript and CSS3
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 3, click ContosoConf.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, and then double-click schedule.htm.
4. Find the following HTML markup near the end of the file:
6. In Solution Explorer, expand the scripts folder, expand the pages folder, and then double-click
schedule.js.
7. In the schedule.js file, replace the downloadSchedule function with the following JavaScript code:
function downloadSchedule() {
var request = $.ajax({
type: "GET",
url: "/schedule/list"
});
request.done(function(response) {
schedule = response.schedule;
displaySchedule();
});
request.fail(function() {
try {
var response = JSON.parse(request.responseText);
alert(response.message);
} catch (e) {
alert("Schedule list not available.");
}
});
}
3. In Internet Explorer, verify that the page displays a list of Conference sessions.
7. Click the star icon next to Diving in at the deep end with Canvas.
13. Verify that the error message Service currently unavailable is displayed.
Results: After completing this exercise, you will have refactored the JavaScript code that sends and
receives data to use the jQuery ajax method.
L6-1
4. On the Windows 8 Start screen click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open,and then click Project/Solution.
7. In Solution Explorer, expand the ContosoConf project and then double-click index.htm.
8. Verify that the <head> element contains the following HTML markup:
<nav class="page-nav">
<div class="container">
<a href="/index.htm" class="active">Home</a>
11. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
12. Verify that the navigation bar at the top of the page contains a row of unstyled links.
/* TODO: nav.page-nav */
nav.page-nav {
background-color: #1d1d1d;
line-height: 6rem;
font-size: 1.7rem;
L6-2 Programming in HTML5 with JavaScript and CSS3
nav.page-nav .container {
display: -ms-flexbox;
display: flexbox;
}
/* TODO: nav.page-nav a */
nav.page-nav a {
display: block;
min-width: 9rem;
padding: 0 1.8rem;
border-right: 1px dotted #3d3d3d;
text-decoration: none;
text-transform: uppercase;
text-align: center;
color: #c3c3c3;
text-shadow: 0 1px 0 #000;
}
nav.page-nav a:first-child {
border-left: 1px dotted #3d3d3d;
}
nav.page-nav a:hover {
color: #e4e4e4;
background-color: black;
}
nav.page-nav .active {
color: #fff;
background: -ms-linear-gradient(#c95656, #8d0606);
L6-3
nav.page-nav .active:hover {
/* Override hover effect for active page link */
color: #fff;
}
nav.page-nav .active:before {
position: absolute;
top: 6rem;
display: block;
height: 0;
width: 0;
margin-left: -1.9rem;
border-top: 2rem solid #8d0606;
border-right: 6.5rem solid transparent;
content: "";
}
nav.page-nav .active:after {
position: absolute;
display: block;
height: 0;
width: 0;
margin-left: 4.3rem;
border-top: 2rem solid #8d0606;
border-left: 6.5rem solid transparent;
content: "";
}
3. Verify that the navigation bar looks similar to the following image:
4. Verify that the <head> element contains the following HTML markup:
<header class="page-header">
<div class="container">
<h1>ContosoConf</h1>
<p class="tag-line">A two-track conference on the latest HTML5
developments</p>
<a class="register" href="/register.htm">
Register<br />
<span class="free">· Free ·</span>
</a>
</div>
</header>
7. In Internet Explorer, verify that the Register link in the page header appears as an ordinary link and is
not styled.
X Task 2: Position the Register Link and Set the Text Styling
1. In Solution Explorer, expand the styles folder, and then double-click header.css.
2. Find the following comment:
3. Modify the CSS rule following this comment, and add the CSS properties shown below in bold:
header.page-header .register {
display: block;
position: absolute;
top: 2rem;
right: 3.5rem;
width: 16rem;
height: 10rem;
padding-top: 6rem;
}
4. Add the following CSS properties shown in bold to the header.page-header .register CSS rule:
header.page-header .register {
display: block;
position: absolute;
top: 2rem;
right: 3.5rem;
width: 16rem;
height: 10rem;
L6-6 Programming in HTML5 with JavaScript and CSS3
padding-top: 6rem;
font-size: 2.7rem;
text-align: center;
text-decoration: none;
text-transform: uppercase;
text-shadow: 0 1px 0 #000;
color: #fff;
}
X Task 3: Style the Register Link Background, Shape, and Rotation Properties
1. Add the following CSS properties shown in bold to the header.page-header .register CSS rule:
header.page-header .register {
display: block;
position: absolute;
top: 2rem;
right: 3.5rem;
width: 16rem;
height: 10rem;
padding-top: 6rem;
font-size: 2.7rem;
text-align: center;
text-decoration: none;
text-transform: uppercase;
text-shadow: 0 1px 0 #000;
color: #fff;
background: -ms-linear-gradient(#a80000, #740404);
background: linear-gradient(#a80000, #740404);
-ms-border-radius: 100%;
border-radius: 100%;
-ms-transform: rotate(6deg);
transform: rotate(6deg);
}
header.page-header .register:hover {
}
3. Add the following CSS properties shown below in bold to this rule:
header.page-header .register:hover {
background: -ms-linear-gradient(#bc0101, #8c0909);
background: linear-gradient(#bc0101, #8c0909);
}
header.page-header .register:before {
}
header.page-header .register:before {
display: block;
position: absolute;
top: -.7rem;
right: -.7rem;
height: 16.8rem;
width: 16.8rem;
content: "";
border: 3px dotted #740404;
-ms-border-radius: 100%;
L6-77
bo
order-radius: 100%;
}
X Task 4: Test
T the Reg
gister Link
1
1. In Solutio
on Explorer, do
ouble-click in
ndex.htm.
2
2. On the D
Debug menu, cclick Start Wiithout Debug
gging.
3
3. In Interne
et Explorer, ve
erify that the R
Register link in the page header looks liike the following image:
FIGUR
RE 6.3: THE ST
TYLED REGIS
STER LINK
4
4. Move the
e mouse over the Register link and veriffy that it changes color.
5
5. Close Inte
ernet Explorerr.
Results: Afte
er completing
g this exercise
e, you will have styled the R
Register link in the header of the Home
page.
L6-8 Programming in HTML5 with JavaScript and CSS3
4. Verify that the <head> element contains the following HTML markup:
5. Verify that the <body> element contains the following HTML markup:
.about p:first-child:first-letter {
font-size: 300%;
float: left;
margin: 0 0.5rem 0 0;
line-height: .8;
color: #aaa;
}
.about p {
text-indent: 3rem;
}
.about p:first-child {
/* Prevents text indenting after drop cap */
text-indent: 0;
margin-top: 0;
}
/* TODO: Blockquote */
.about blockquote {
font-size: 1.2em;
padding: 0 0 0 6rem;
margin: 0;
font-style: italic;
position: relative;
}
.about blockquote:before {
content: '\201C';
position: absolute;
font-size: 10rem;
font-family: serif;
left: 0;
top: -1rem;
line-height: 1;
}
R
Results: After completing this exercise, you
y will have styled the textt on the Abou
ut page.
L7-1
3. Log on to the 20480A-SEA-DEV11-07 virtual machine as Student with the password Pa$$w0rd.
4. On the Windows 8 Start screen click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
6. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 1, click ContosoConf.sln, and
then click Open.
7. In Solution Explorer, expand the ContosoConf project node, and then expand the scripts folder.
8. Double-click Object.inherit.js.
// TODO: Create a variable named `factory`, assign it a new object who's prototype
is `this`.
// TODO: Add a method called `create` to `factory`, that does the following
factory.create = function() {
6. After the comment, add a blank line followed by the following JavaScript code:
};
copyOwnProperties(additionalProperties, factory);
return factory;
11. In the inherit function, find the comment that starts with the following line:
return instance;
Object.inherit = inherit;
(function () {
} ());
2. After the comment, add the following line (including the quotes):
"use strict";
Results: After completing this exercise, you will have written the Object.inherit utility function that you
will use in later exercises to structure the code for the web application. You will also have modified the
scope for this function, and specified that the code should run by using strict mode.
L7-4 Programming in HTML5 with JavaScript and CSS3
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 2, click ContosoConf.sln, and
then click Open.
3. Expand the ContosoConf project, expand the scripts folder, and then expand the pages folder.
4. Double-click schedule.js.
2. Delete the startDownload, downloadDone, downloadFailed, addAll, and add functions that follow
this comment.
3. Add the following JavaScript code shown in bold to the ScheduleList object (note that there is a
comma after the closing brace of the initialize function):
downloadFailed: function () {
alert("Could not retrieve schedule data at this time. Please try again
later.");
},
addAll: function (itemsArray) {
itemsArray.forEach(this.add, this);
},
add: function (itemData) {
var item = ScheduleItem.create(itemData, this.localStarStorage);
this.element.appendChild(item.element);
}
});
2. Delete this block of JavaScript code, and then replace it with the following code:
The Schedu
ule page should still displayy the list of sesssions for the conference, like this:
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
9. Verify that the HTML markup contains the following <img> element:
10. Verify that the HTML markup contains the following <script> elements:
11. In Solution Explorer, expand the scripts folder and then expand the pages folder.
13. Verify that the JavaScript file contains the following line of code:
// TODO: Add event listeners for element "dragover" and "drop" events.
// handle with this.handleDragOver.bind(this) and this.handleDrop.bind(this)
if (this.isImageType(file.type)) {
this.readFile(file).done(this.displayImage);
} else {
alert("Please drop an image file.");
}
// TO
ODO: Start reading
r the file as a Da
ataURL
6
6. After the comment, inssert the follow
wing JavaScrip
pt:
reade
er.readAsDat
taURL(file);
X Task 5: Test
T the Spe
eaker Badge Page
1
1. In Solutio
on Explorer, do
ouble-click sp
peaker-badge
e.htm.
2
2. On the D
Debug menu, cclick Start Wiithout Debug
gging.
3
3. In Interne
et Explorer, if the message Intranet settin
ngs are turned
d off by defau
ult appears, click Don’t
show thiss message agaain.
4
4. On the W
Windows taskb
bar, click File E
Explorer and browse to E:\\Labfiles\Ressources.
5
5. Drag-and
d-drop mark-hanson.jpg ffrom File Explo
orer, onto the
e empty rectangle in Intern
net Explorer.
FIGUR
RE 8.1: THE SP DGE PAGE WITH THE SPEA
PEAKER BAD AKER'S PHOT
TO
6
6. Close Inte
ernet Explorerr and File Explorer.
Results: Afte
er completing
g this exercise
e, you will have implemente
ed functionality that enable
es the user to
drag-and-drrop an image from File Exp plorer into the
e web page.
L8-4 Programming in HTML5 with JavaScript and CSS3
4. Double-click index.htm.
6. After the second line of the comment, add the following HTML markup:
<video src="http://ak.channel9.msdn.com/ch9/265b/9a76fccd-941e-4285-ad00-
9ea200aa265b/MIX09KEY01_high_ch9.mp4"></video>
2. Double-click video.js.
3. Find the following comment:
controls.style.display = "block";
6. After the second line of comment, add the following JavaScript code:
L8-5
video.play();
playButton.style.display = "none";
pauseButton.style.display = "";
video.pause();
pauseButton.style.display = "none";
playButton.style.display = "";
// play click
// pause click
time.textContent = formatTime(video.currentTime);
// video timeupdate
3. In Internet Explorer, wait for the Play button to appear underneath the video.
4. Click Play.
L8-6 Programming in HTML5 with JavaScript and CSS3
5. Verify that the video begins to play and that the current video time is displayed.
6. Click Pause.
7. Verify that the video pauses.
Results: After completing this exercise, you will have added a video player to the Home page.
L8-7
5. Verify that the HTML markup contains the following <h2> element:
<h2 id="distance"></h2>
6. In Solution Explorer, expand the scripts folder, and then expand the pages folder.
7. Double-click location.js.
var conferenceLocation = {
latitude: 47.6097, // decimal degrees
longitude: 122.3331 // decimal degrees
};
X Task 2: Get the Current Location of the User Viewing the Page
1. In location.js, find the following comment:
navigator.geolocation.getCurrentPosition(updateUIForPosition, error);
3. In Internet Explorer, if the message localhost wants to track your location appears, click Allow
once.
5. Verify that the page displays the distance to the conference venue, in miles (the actual value will vary)
L8-8 Programming in HTML5 with JavaScript and CSS3
Results: After completing this exercise, you will have a Location page that displays the distance of the
user from the conference venue.
L9-1
2. Start the 20480A-SEA-DEV11-09 virtual machine if it is not already running, and log on as Student
with the password Pa$$w0rd.
8. In the Website Data Settings dialog box, click the Caches and databases tab.
9. Select the Allow website caches and databases check box, and then click OK.
12. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
13. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
14. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 1, click ContosoConf.sln,
and then click Open.
15. In Solution Explorer, expand the ContosoConf project node, and then double-click
appcache.manifest.
/index.htm
/about.htm
/location.htm
/schedule.htm
21. Add the manifest attribute to the <html> element, as shown in bold below:
23. Add the manifest attribute to the <html> element, as shown in bold below:
if (!navigator.onLine) {
hideLinksThatRequireOnline();
}
document.body.onoffline = hideLinksThatRequireOnline;
document.body.ononline = showLinks;
3. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
5. Expand the Windows notification area, right-click IIS Express, and then click Exit.
L9-3
FIGURE 9.1: THE IIS EXPRESS ICON IN THE WINDOWS NOTIFICATION AREA
6. In the Confirmation dialog box, click Yes.
8. Verify that the page loads and displays the schedule information.
9. Wait five seconds, and then verify that the web site navigation bar no longer displays the Register
link.
11. Verify that the page loads and displays the information describing the conference.
12. Verify that the web site navigation bar no longer displays the Register link.
Results: After completing this exercise, you will have modified the web application and made the
Home, About, Schedule, and Location pages available offline.
L9-4 Programming in HTML5 with JavaScript and CSS3
5. Expand the Windows notification area, right-click IIS Express, and then click Exit.
6. In the Confirmation dialog box, click Yes.
7. In Internet Explorer, click the star icon in the Registration box, and verify that the icon is now colored
yellow.
8. Click Refresh.
9. Verify that the star icon for Registration is now colored white.
this.localStorage.setItem("stars", JSON.stringify(this.sessions));
if (json) {
try {
this.sessions = JSON.parse(json) || [];
} catch (exception) {
this.sessions = [];
}
} else {
L9-5
this.sessions = [];
}
X Task 4: Use the local storage wrapper to save and load data in the Schedule page
1. In Solution Explorer, expand the scripts folder, then expand the pages folder, and then double-click
schedule.js.
if (localStarStorage.isStarred(this.id)) {
this.element.classList.add(this.starredClass);
}
this.localStarStorage.removeStar(this.id);
this.localStarStorage.addStar(this.id);
CACHE MANIFEST
# version 2
7. Expand the Windows notification area, right-click IIS Express, and then click Exit.
9. In Internet Explorer, click the star icon in the Registration box, and verify that the icon is now colored
yellow.
11. Verify that the star icon for Registration is still colored yellow.
L9-6 Programming in HTML5 with JavaScript and CSS3
Results: After completing this exercise, you will have updated the Schedule page to locally record
starred sessions.
L10-1
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
7. In Visual Studio, in Solution Explorer, expand the ContosoConf project, and then double-click
about.htm.
8. On the Debug menu, click Start Without Debugging.
9. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
10. On the Tools menu, point to Print, and then click Print Preview...
11. In the Print Preview window, verify that the preview looks like the following image:
L10-2 Programming in HTML5 with JavaScript and CSS3
The Print Preview version of the About page looks like this:
3. In the Add New Item - ContosoConf dialog box, in the left pane, expand the Visual C# node, and
then click Web.
6. Click Add.
nav.page-nav,
header.page-header,
footer.page-footer {
display: none;
}
.container {
padding: 0;
max-width: none;
}
3. On the Tools menu, point to Print, and then click Print Preview.
4. Verify that the Print Preview window displays the following image:
L10-4 Program
mming in HTML5 with JavaScript and CSSS3
7. In the Resize Browser dialog box, in the Width box, type 480.
11. Verify that the Home page looks similar to the following image:
L10-6 Program
mming in HTML5 with JavaScript and CSSS3
X Task 2: Im
mplement Sttyles for Haand-Held De
evices and S
Smartphone
es
1. In Solution Explorer, expand the style
es folder, and then double-click mobile.ccss.
L10-7
4. In the ContosoConf – F12 window, on the Tools menu, point to Resize, and then click 1280×1024.
5. Press F12.
8. In the ConttosoConf – F1
12 window, on the Tools m
menu, point to
o Resize, and then click 48
80×800.
9. Press F12.
n bar is displa
0. Verify that tthe navigation
10 ed form factor, and that the Register
ayed correctlyy in the reduce
link does noot appear in the header of the web page e.
L10-99
The Hom
me page should look like this in the reduced size window:
1 Close Inte
11. ernet Explorerr.
L10-10 Programming in HTML5 with JavaScript and CSS3
Results: After completing this exercise, you will have a website that adapts to different screen sizes.
L11-1
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
7. In Solution Explorer, expand the ContosoConf project node, and then double-click location.htm.
12. If the message localhost wants to track your location appears, click Allow once.
14. If the message Intranet settings are turned off by default appears, click Don’t show this message
again.
X Task 2: Co
omplete the
e SVG venue
e map
1. In Visual Stu
udio, in location.htm, find
d the following
g comment:
<!-- Ro
oom B -->
2. After the co
omment, add the following
g markup:
X Task 3: Ad
dd interactivity to the v
venue map
1. In Solution Explorer, dou
uble-click loca
ation.htm.
<div id
d="room-a-innfo" style="
"display: none">
<h2>Room A</h2>
<p>Ca
apacity: 2500</p>
<p>Po
opular sessiions in here
e:</p>
<ul>
<li
i>Diving in at the deepp end with Ca
anvas</li>
<li
i>Real-worldd Applicatio
ons of HTML5 APIs</li>
<li
i>Transformss and Animat
tions</li>
</ul>
>
</div>
<div id
d="room-b-innfo" style="
"display: none">
L11-3
<h2>Room B</h2>
<p>Capacity: 230</p>
<p>Popular sessions in here:</p>
<ul>
<li>Building Responsive UIs</li>
<li>Getting to Grips with JavaScript</li>
<li>A Fresh Look at Layouts</li>
</ul>
</div>
3. In Solution Explorer, expand the styles folder, expand the pages folder, and then double-click
location.css.
.room:hover rect {
fill: #b1f8b0;
}
5. In Solution Explorer, expand the scripts folder, expand the pages folder, and then double-click
location-venue.js.
9. After the second line of this comment, add the following JavaScript code:
4. Scroll down to the venue map and hover the mouse over Room A.
5. Verify that the venue map looks similar to the following image:
L11-4 Program
mming in HTML5 with JavaScript and CSSS3
The informa
ation displaye
ed for Room B should look like this:
7. Close Intern
net Explorer.
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 2 click ContosoConf.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, and then double-click speaker-badge.htm.
<canvas
width="500"
height="200"
style="border: 1px solid #888"
data-speaker-id="234724"
data-speaker-name="Mark Hanson">
</canvas>
this.canvas = element.querySelector("canvas");
this.context = this.canvas.getContext("2d");
6. After the last line of this comment, add the following JavaScript code:
this.drawBackground();
this.drawTopText();
this.drawSpeakerName();
if (image) {
this.drawSpeakerImage(image);
} else {
this.drawImagePlaceholder();
}
this.drawBarCode(this.speakerId);
8. After this co
omment, add the following
g JavaScript co
ode:
this.co
ontext.fillS
Style = "white";
this.co
ontext.fillR
Rect(0, 0, t
this.canvas.w
width, this.
.canvas.heig
ght);
// TODO
O: Draw the image on th
he canvas
10
0. After the last line of this comment, add the followin
ng JavaScript code:
var siz
ze = Math.mi
in(image.wid
dth, image.he
eight);
var sourceX = imag
ge.width / 2 - size / 2;
var sourceY = imag
ge.height / 2 - size / 2;
this.co
ontext.drawI
Image(image, sourceX, so
ourceY, size
e, size, 20, 20, 160, 160);
// TODO
O: Draw this
s.speakerNam
me on the canvas
12. After the last line of this comment, add the followin
ng JavaScript code:
this.co
ontext.font = "40px san
ns-serif";
this.co
ontext.fillS
Style = "bla
ack";
this.co
ontext.textB
Baseline = "
"top";
this.co
ontext.textA
Align = "lef
ft";
this.co
ontext.fillT
Text(this.sp
peakerName, 200, 60);
X Task 3: Te
est the application
1. In Solution Explorer, dou
uble-click spea
aker-badge.h
htm.
2. On the Deb
bug menu, click Start With
hout Debugg
ging.
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
6. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 1, click ContosoConf.sln, and
then click Open.
7. In Solution Explorer, expand the ContosoConf project node, and then double-click feedback.htm.
12. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
13. Verify that the Feedback form is displayed and has five star icons next to each question.
2. Update the following CSS rule, and add the code shown below in bold:
.star:hover,
.star.hover {
background-position: 0 -15px;
/* TODO: Scale transform by 1.3 */
transform: scale(1.3, 1.3);
/* TODO: Transition the transform property over 0.5 seconds */
transition: transform .5s;
}
3. Update the following CSS rule, and add the code shown below in bold:
.star {
background-image: url(../images/stars.png);
width: 15px;
height: 15px;
cursor: pointer;
margin: .1rem;
-ms-flex: 0 0 15px;
flex: 0 0 15px;
/* TODO: Transition the transform property over 0.5 seconds */
transition: transform .5s;
}
4. Update the following CSS rule, and add the code shown below in bold:
.star.selected {
background-position: 0 -30px;
/* TODO: Scale transform by 1.3 */
transform: scale(1.3, 1.3);
}
header.page-header .register:hover {
color: #fff;
background: -ms-linear-gradient(#bc0101, #8c0909);
background: linear-gradient(#bc0101, #8c0909);
/* TODO: rotate to 16 degrees and scale by 1.1 */
transform: rotate(16deg) scale(1.1,1.1);
/* TODO: Transition the transform property over 1 second */
transition: transform 1s;
}
3. Update the following CSS rule, and add the code shown below in bold:
L12-3
header.page-header .register {
display: block;
position: absolute;
top: 20px;
right: 35px;
width: 160px;
height: 100px;
padding-top: 60px;
opacity: 0.8;
font-size: 2.7rem;
color: #fff;
text-align: center;
text-decoration: none;
text-transform: uppercase;
-ms-border-radius: 100%;
border-radius: 100%;
-ms-text-shadow: 0 1px 0 #000;
text-shadow: 0 1px 0 #000;
-ms-transform: rotate(6deg);
transform: rotate(6deg);
background: -ms-linear-gradient(#a80000, #740404);
background: linear-gradient(#a80000, #740404);
/* TODO: Transition the transform property over 1 second */
transition: transform 1s;
}
7. Click Home.
8. Move the mouse over the Register Free link and verify that it rotates and enlarges.
Results: After completing this exercise, the Register button will rotate and the feedback stars will
animate when the mouse moves over them.
L12-4 Programming in HTML5 with JavaScript and CSS3
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 2, click ContosoCon.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, expand the styles folder, expand the pages
folder, and then double-click feedback.css.
@keyframes send {
0% {
transform: scale(1);
}
50% {
transform: scale(.8);
}
100% {
transform: translate(0, -1000px);
}
}
7. After this comment, add the following set of properties and values:
animation-name: send;
animation-duration: 1s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
// TODO: Trigger the animation by adding the "sending" CSS class to the form
form.classList.add("sending");
Results: After completing this exercise, submitting the conference feedback form will trigger an
animation that makes the form fly off the page.
L13-1
3. Log on to the 20480A-SEA-DEV11-13 virtual machine as Student with the password Pa$$w0rd.
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
6. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 1, click ContosoConf.sln, and
then click Open.
8. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.
9. Click Live.
10. In the Webpage Error dialog box, click No.
11. Verify that the Live page looks like the following image:
L13-2 Program
mming in HTML5 with JavaScript and CSSS3
<form aaction="#">
<la
abel for="assk-question-
-text">Ask a question</l
label>
<input id="askk-question-t
text" type="t
text" />
<button type=""submit">Ask
k</button>
</form>>
<ul>
<!-- Questionss will be displayed here
e when recei
ived by the web socket. -->
</ul>
<script
t src="/scri
ipts/pages/live.js" type
e="text/java
ascript"></s
script>
16
6. In Solution Explorer, expand the scrip
pts folder, exp
pand the page
es folder, and then double--click
live.js.
17. Verify that tthe file contaiins the following JavaScriptt code:
var Liv
vePage = Obj
ject.inherit
t({
X Task 2: Re
eceive messsages by usiing a web so
ocket
1. In live.js, fin
nd the following commentt:
// TODO
O: Create a web socket connection t
to ws://loca
alhost:55981
1/live/socket
t.ashx
L13-3
this.socket.onmessage = this.handleSocketMessage.bind(this);
if (message.questions) {
this.handleQuestionsMessage(message);
}
// TODO: Display each question in the page, using the displayQuestion function.
if (message.questions) {
message.questions.forEach(this.displayQuestion, this);
}
3. In Internet Explorer, once the page has loaded, wait five seconds.
4. Verify that the page displays the following four questions:
• What are some good resources for getting started with HTML5?
• Can you explain more about the Web Socket API, please?
• This is an #&!%!* inappropriate message!!
Results: After completing this exercise, you will have added JavaScript code to the Live web page to
receive questions from a web socket and to display them.
L13-5
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 2, click ContosoConf.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, expand the scripts folder, expand the pages
folder, and then double-click live.js.
var message = {
ask: text
};
this.socket.send(json);
Results: After completing this exercise, you will have modified the Live question page to enable users to
ask questions by sending messages to the server by using the web socket.
L13-7
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 3, click ContosoConf.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, expand the scripts folder, expand the pages
folder, and then double-click live.js.
//item.appendChild(this.createReportLink());
item.appendChild(this.createReportLink());
6. Verify that the What are some good resources for getting started with HTML5? question is removed
from the page.
Results: After completing this exercise, you will have added a feature to the Live page that enables
users to report inappropriate questions and causes the application to remove them.
L14-1
3. Log on to the 20480-SEA-DEV11-14 virtual machine as Student with the password Pa$$w0rd.
4. On the Windows 8 Start screen, click the Visual Studio 2012 tile.
5. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
6. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 1, click ContosoConf.sln, and
then click Open.
7. In Solution Explorer, expand the ContosoConf project, and then double-click speaker-badge.htm.
<div class="busy">
<p>Creating badge. Please wait...</p>
</div>
10. In Solution Explorer, expand the scripts folder, and then double-click grayscale.js.
11. Verify that the file contains the following JavaScript function:
this.readFile(file)
.pipe(this.loadImage)
.pipe(grayscaleImage)
.done(this.drawBadge, this.notBusy);
L14-2 Programming in HTML5 with JavaScript and CSS3
9. Drag mark-hanson-large.jpg from Windows Explorer into Internet Explorer and drop it onto the
canvas with the label Drag your profile photo here.
10. Verify that you cannot scroll the page or move to another page until after the image has been
displayed. This may take several seconds.
11. If Internet Explorer displays the message localhost is not responding due to a long-running script,
wait for the message to disappear.
5. Add the following JavaScript code to this file, after the comment at the top:
8. Insert the following code shown in bold between these two statements:
2. In grayscale-worker.js, underneath the existing code, paste the JavaScript code for the
grayscalePixel function from the clipboard.:
11. Verify that you can scroll the page up and down while and image is being processed.
Results: After completing this exercise, you will have a created a web page that remains responsive
while slow image processing code runs in a web worker.
L14-5
2. In the Open Project dialog box, browse to E:\Labfiles\Starter\Exercise 2, click ContosoConf.sln, and
then click Open.
3. In Solution Explorer, expand the ContosoConf project, and then double-click speaker-badge.htm.
<div class="busy">
<p>Creating badge. Please wait...</p>
</div>
5. Modify this HTML markup by adding the following code shown in bold:
<div class="busy">
<p>Creating badge. Please wait...</p>
<progress value="0" max="100"></progress>
</div>
6. In Solution Explorer, expand the scripts folder, expand the pages folder, and then double-click
speaker-badge.js.
this.busyElement = element.querySelector(".busy");
this.progress = element.querySelector("progress");
9. Add the following JavaScript code shown in bold to the SpeakerBadgePage object, after the
initialize function:
11. After the comment, update the code by adding the line shown in bold:
this.readFile(file)
.pipe(this.loadImage)
.pipe(grayscaleImage)
.progress(this.updateProgress)
.done(this.drawBadge, this.notBusy);
3. Update the message event callback function and add the following code shown in bold:
conference.grayscaleImage = function(image) {
...
var imageData = getImageData(context, image);
var handleMessage = function (event) {
var message = event.data;
if (message.progress) {
deferred.notifyWith(this, [message.progress]);
} else if (message.done) {
var updatedImageData = message.done;
// Update the canvas with the gray scaled image data.
context.clearRect(0, 0, canvas.width, canvas.height);
context.putImageData(updatedImageData, 0, 0);
deferred.resolveWith(this, [canvas]);
}
};
var worker = new Worker("/scripts/grayscale-worker.js");
...
};
5
5. Press F12
2, and then clo
ose Internet EExplore.
6
6. In Visual Studio, in Solu
ution Explorer, double-click speaker-ba
adge.htm.
7
7. On the Debug menu, cclick Start Witthout Debugg
ging.
8
8. On the taaskbar, click Fiile Explorer.
9
9. Browse to
o the E:\Labfiile\Resourcess folder.
1 Drag marrk-hanson-la
10. arge.jpg from
m File Explorer into Internet Explorer and drop it onto the canvas
with the llabel Drag yo
our profile ph
hoto here.
FIGUR
RE 14.1: PROG
GRESS BAR FO
OR THE SPEA
AKER BADGE
E PAGE
1 Close Inte
12. ernet Explorerr.
Results: Afte
er completingg this exercise
e, you will have modified th
he Speaker Ba
adge page to
o display a
progress barr while an imaage is being p
processed.