Sei sulla pagina 1di 627

MCT USE ONLY.

STUDENT USE PROHIBITED


O F F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T

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.

Microsoft and the trademarks listed at


http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of
the Microsoft group of companies. All other trademarks are property of their respective owners.

Product Number: 20480A


Part Number (if applicable):

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.

a. If you are a Authorized Learning Center:


i. If the Licensed Content is in digital format for each license you acquire you may either:
1. install one (1) copy of the Licensed Content in the form provided to you on a dedicated, secure
server located on your premises where the Authorized Training Session is held for access and
use by one (1) End User attending the Authorized Training Session, or by one (1) MCT teaching
the Authorized Training Session, or
2. install one (1) copy of the Licensed Content in the form provided to you on one (1) Classroom
Device for access and use by one (1) End User attending the Authorized Training Session, or by
one (1) MCT teaching the Authorized Training Session.
ii. You agree that:
1. you will acquire a license for each End User and MCT that accesses the Licensed Content,
2. each End User and MCT will be presented with a copy of this agreement and each individual
will agree that their use of the Licensed Content will be subject to these license terms prior to
their accessing the Licensed Content. Each individual will be required to denote their
acceptance of the EULA in a manner that is enforceable under local law prior to their accessing
the Licensed Content,
3. for all Authorized Training Sessions, you will only use qualified MCTs who hold the applicable
competency to teach the particular MOC Course that is the subject of the training session,
4. you will not alter or remove any copyright or other protective notices contained in the
Licensed Content,
MCT USE ONLY. STUDENT USE PROHIBITED
5. you will remove and irretrievably delete all Licensed Content from all Classroom Devices and
servers at the end of the Authorized Training Session,
6. you will only provide access to the Licensed Content to End Users and MCTs,
7. you will only provide access to the Trainer Content to MCTs, and
8. any Licensed Content installed for use during a training session will be done in accordance
with the applicable classroom set-up guide.

b. If you are a MPN Member.


i. If the Licensed Content is in digital format for each license you acquire you may either:
1. install one (1) copy of the Licensed Content in the form provided to you on (A) one (1)
Classroom Device, or (B) one (1) dedicated, secure server located at your premises where
the training session is held for use by one (1) of your employees attending a training session
provided by you, or by one (1) MCT that is teaching the training session, or
2. install one (1) copy of the Licensed Content in the form provided to you on one (1)
Classroom Device for use by one (1) End User attending a Private Training Session, or one (1)
MCT that is teaching the Private Training Session.
ii. You agree that:
1. you will acquire a license for each End User and MCT that accesses the Licensed Content,
2. each End User and MCT will be presented with a copy of this agreement and each individual
will agree that their use of the Licensed Content will be subject to these license terms prior
to their accessing the Licensed Content. Each individual will be required to denote their
acceptance of the EULA in a manner that is enforceable under local law prior to their
accessing the Licensed Content,
3. for all training sessions, you will only use qualified MCTs who hold the applicable
competency to teach the particular MOC Course that is the subject of the training session,
4. you will not alter or remove any copyright or other protective notices contained in the
Licensed Content,
5. you will remove and irretrievably delete all Licensed Content from all Classroom Devices and
servers at the end of each training session,
6. you will only provide access to the Licensed Content to End Users and MCTs,
7. you will only provide access to the Trainer Content to MCTs, and
8. any Licensed Content installed for use during a training session will be done in accordance
with the applicable classroom set-up guide.

c. If you are an End User:


You may use the Licensed Content solely for your personal training use. If the Licensed Content is in
digital format, for each license you acquire you may (i) install one (1) copy of the Licensed Content in
the form provided to you on one (1) Personal Device and install another copy on another Personal
Device as a backup copy, which may be used only to reinstall the Licensed Content; or (ii) print one (1)
copy of the Licensed Content. You may not install or use a copy of the Licensed Content on a device
you do not own or control.
MCT USE ONLY. STUDENT USE PROHIBITED
d. If you are a MCT.
i. For each license you acquire, you may use the Licensed Content solely to prepare and deliver an
Authorized Training Session or Private Training Session. For each license you acquire, you may
install and use one (1) copy of the Licensed Content in the form provided to you on one (1) Personal
Device and install one (1) additional copy on another Personal Device as a backup copy, which may
be used only to reinstall the Licensed Content. You may not install or use a copy of the Licensed
Content on a device you do not own or control.

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.3 Reproduction/Redistribution Licensed Content. Except as expressly provided in the applicable


installation and use rights above, you may not reproduce or distribute the Licensed Content or any portion
thereof (including any permitted modifications) to any third parties without the express written permission
of Microsoft.

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.

13. APPLICABLE LAW.


a. United States. If you acquired the Licensed Content in the United States, Washington state law governs
the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws
principles. The laws of the state where you live govern all other claims, including claims under state
consumer protection laws, unfair competition laws, and in tort.

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.

This limitation applies to


o anything related to the Licensed Content, services made available through the Licensed Content, or
content (including code) on third party Internet sites or third-party programs; and
o claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,
or other tort to the extent permitted by applicable law.

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.

LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous


pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement
à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y
compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne:
• tout ce qui est relié au le contenu sous licence , aux services ou au contenu (y compris le code)
figurant sur des sites Internet tiers ou dans des programmes tiers ; et
• les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité
stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.

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.

Revised December 2011


MCT USE ONLY. STUDENT USE PROHIBITED
Course Title
x
MCT USE ONLY. STUDENT USE PROHIBITED
Course Title xi

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.

John Sharp – Content Developer


John Sharp gained an honors degree in Computing from Imperial College, London. He has been
developing software and writing training courses, guides, and books for over 25 years. John has
experience in a wide range of technologies, from database systems and UNIX through to C, C++ and C#
applications for the .NET Framework, together with Java and JavaScript development. He has authored
several books for Microsoft Press, including 6 editions of C# Step By Step, Windows Communication
Foundation Step By Step, and the J# Core Reference.

Andrew Davey – Subject Matter Expert


Andrew Davey has a Bachelors degree in Computer Science and has been working in the software
industry for 10 years, primarily with Microsoft technologies.

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 Olsen – Subject Matter Expert


Andy Olsen studied Physics in Southampton University in the UK, and has been working in IT for more
than 25 years. He has been working with the .NET Framework since Beta 1 days and has written and
designed numerous Microsoft courses covering a wide range of subjects, including ASP.NET, WPF, WCF,
ADO.NET, XML, and HTML5.

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.

Dan Maharry - Subject Matter Expert


Dan Maharry is an experienced technical author with over a dozen books to his name and many more as
technical reviewer and editor for a variety of publishers including Wrox, Apress, Microsoft Press and
O'Reilly. He's also a .NET developer with past stints for the dotCoop TLD registry and various web
development houses under his belt.

David Day - Subject Matter Expert


David Day is a senior web developer for a local authority in the United Kingdom. He builds web
applications that combine MVC3, the .NET Framework 4, NHibernate, SQL Server, HTML5, CSS, JavaScript,
and jQuery.

Carsten Thomsen – Technical Reviewer


Carsten Thomsen is currently doing SharePoint 2010 development, but his interests are varied when it
comes to IT and includes development of ASP.NET, Windows Forms, Windows Store, Windows Phone and
other types of applications and components.
MCT USE ONLY. STUDENT USE PROHIBITED
xii Course Title

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

Module 2: Creating and Styling HTML Pages


Lesson 1: Creating an HTML5 Page page 3
Lesson 2: Styling an HTML5 Page page 13
Lab: Creating and Styling HTML5 Pages page 26

Module 3: Introduction to JavaScript


Lesson 1: Overview of JavaScript page 3
Lesson 2: Introduction to the Document Object Model page 21
Lesson 3: Introduction to jQuery page 30
Lab: Displaying Data and Handling Events by Using JavaScript page 41

Module 4: Creating Forms to Collect and Validate User Input


Lesson 1: Creating HTML5 Forms page 3
Lesson 2: Validating User Input by Using HTML5 Attributes page 9
Lesson 3: Validating User Input by Using JavaScript page 16
Lab: Creating a Form and Validating User Input page 22

Module 5: Communicating with a Remote Server


Lesson 1: Sending and Receiving Data by Using the
XMLHTTPRequest Object page 3
Lesson 2: Sending and Receiving Data by Using the jQuery Library page 13
Lab: Communicating with a Remote Server page 19

Module 6: Styling HTML5 by Using CSS3


Lesson 1: Styling Text by Using CSS3 page 3
Lesson 2: Styling Block Elements page 9
Lesson 3: Pseudo-classes and Pseudo-elements page 20
Lesson 4: Enhancing Graphical Effects by Using CSS3 page 27
Lab: Styling Text and Block Elements by Using CSS3 page 34

Module 7: Creating Objects and Methods by Using JavaScript


Lesson 1: Writing Well-Structured JavaScript Code page 3
Lesson 2: Creating Custom Objects page 10
Lesson 3: Extending Objects page 18
MCT USE ONLY. STUDENT USE PROHIBITED
xiv Course Title

Lab: Refining Code for Maintainability and Extensibility page 24

Module 8: Creating Interactive Pages by Using HTML5 APIs


Lesson 1: Interacting with Files page 3
Lesson 2: Incorporating Multimedia page 10
Lesson 3: Reacting to Browser Location and Content page 17
Lesson 4: Debugging and Profiling a Web Application page 24
Lab: Creating Interactive Pages by Using HTML5 APIs page 31

Module 9: Adding Offline Support to Web Applications


Lesson 1: Caching Offline Data by Using the Application Cache API page 3
Lesson 2: Persisting User Data by Using the Local Storage API page 14
Lab: Adding Offline Support to Web Applications page 21

Module 10: Implementing an Adaptive User Interface


Lesson 1: Supporting Multiple Form Factors page 3
Lesson 2: Creating an Adaptive User Interface page 9
Lab: Implementing an Adaptive User Interface page 19

Module 11: Creating Advanced Graphics


Lesson 1: Creating Interactive Graphics by Using SVG page 3
Lesson 2: Programmatically Drawing Graphics by Using the
Canvas API page 22
Lab: Creating Advanced Graphics page 34

Module 12: Animating the User Interface


Lesson 1: Applying CSS Transitions page 3
Lesson 2: Transforming Elements page 11
Lesson 3: Applying CSS Key-frame Animations page 25
Lab: Animating the User Interface page 34

Module 13: Implementing Real-time Communication by Using Web Sockets


Lesson 1: Introduction to Web Sockets page 3
Lesson 2: Using the Web Socket API page 7
Lab: Performing Real-time Communication by Using Web Sockets page 15

Module 14: Performing Background Processing by Using Web Workers


Lesson 1: Understanding Web Workers page 3
Lesson 2: Performing Asynchronous Processing by Using
Web Workers page 9
Lab: Creating a Web Worker Process page 18

Lab Answer Keys


MCT USE ONLY. STUDENT USE PROHIBITED
Course Title xv

Module 1 Lab: Exploring the Contoso Conference Application page 1


Module 2 Lab: Creating and Styling HTML5 Pages page 1
Module 3 Lab: Displaying Data and Handling Events by Using
JavaScript page 1
Module 4 Lab: Creating a Form and Validating User Input page 1
Module 5 Lab: Communicating with a Remote Server page 1
Module 6 Lab: Styling Text and Block Elements by Using CSS3 page 1
Module 7 Lab: Refining Code for Maintainability and Extensibility page 1
Module 8 Lab: Creating Interactive Pages by Using HTML5 APIs page 1
Module 9 Lab: Adding Offline Support to Web Applications page 1
Module 10 Lab: Implementing an Adaptive User Interface page 1
Module 11 Lab: Creating Advanced Graphics page 1
Module 12 Lab: Animating the User Interface page 1
Module 13 Lab: Performing Real-time Communication by Using
Web Sockets page 1
Module 14 Lab: Creating a Web Worker Process page 1
MCT USE ONLY. STUDENT USE PROHIBITED
 
MCT USE ONLY. STUDENT USE PROHIBITED
About This Course i

About This Course


This section provides a brief description of the course, audience, suggested prerequisites, and course
objectives.

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

• 1 month experience creating Windows client applications

• 1 month of experience using Visual Studio 2010 or 2012


This course is not intended for developers with three or more months of HTML5 coding experience.

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:

• Understand the basic HTML document structure:

o Use HTML tags to display text content.

o Use HTML tags to display graphics.

o Use HTML APIs.

• Understand how to style common HTML elements using CSS, including:

o Separating presentation from content.

o Managing content flow.

o Managing positioning of individual elements.


MCT USE ONLY. STUDENT USE PROHIBITED
ii About This Course

o Managing content overflow.

o Basic CSS styling.

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.

• Add interactivity to an HTML5 page by using JavaScript.


• Create HTML5 forms by using different input types, and validate user input by using HTML5
attributes and JavaScript code.

• Send and receive data to and from a remote data source by using XMLHTTPRequest objects and
jQuery AJAX operations.

• Style HTML5 pages by using CSS3.

• Create well-structured and easily-maintainable JavaScript code.

• Use common HTML5 APIs in interactive Web applications.

• Create Web applications that support offline 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.

• Enhance the user experience by adding animations to an HTML5 page.


• Use Web Sockets to send and receive data between a Web application and a server.

• Improve the responsiveness of a Web application that performs long-running operations by


using Web Worker processes.

Course Outline
The course outline is as follows:

Module 1, “Overview of HTML and CSS"

Module 2, “Creating and Styling HTML Pages"

Module 3, “Introduction to JavaScript"


Module 4, “Creating Forms to Collect and Validate User Input"

Module 5, “Communicating with a Remote Server"

Module 6, “Styling HTML5 by Using CSS3"


Module 7, “Creating Objects and Methods by Using JavaScript"

Module 8, “Creating Interactive Pages by Using HTML5 APIs"

Module 9, “Adding Offline Support to Web Applications"


Module 10, “Implementing an Adaptive User Interface"

Module 11, “Creating Advanced Graphics"


MCT USE ONLY. STUDENT USE PROHIBITED
About This Course iii

Module 12, “Animating the User Interface"

Module 13, “Implementing Real-time Communication by Using Web Sockets"


Module 14, “Performing Background Processing by Using Web Workers"

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.

• Lab Answer Keys: provide step-by-step lab solution guidance.


Course Companion Content: searchable, easy-to-browse digital content with integrated premium
online resources that supplement the Course Handbook.

• 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

• To provide additional comments or feedback on the course, send an email to


support@mscourseware.com. To inquire about the Microsoft Certification Program, send an
email to mcphelp@microsoft.com.
MCT USE ONLY. STUDENT USE PROHIBITED
About This Course v

Virtual Machine Environment


This section provides the information for setting up the classroom environment to support the business
scenario of the course.

Virtual Machine Configuration


In this course, you will use Microsoft® Hyper-V™to perform the labs.

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:

1. On the virtual machine, on the Action menu, click Close.

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:

Virtual machine Role


MSL-TMG1 Gateway computer for Internet access

20480A-SEA-DEV11-<Module Development computer used for building web


#> applications. Each module uses a different copy of
this virtual machine, called 20480A-SEA-DEV-01
for module 1, 20480A-SEA-DEV11-02 for module
2, and so on.

Software Configuration
The following software is installed on each VM:
• Microsoft Windows 8 Enterprise

• Microsoft Visual Studio 2012 Ultimate

• Microsoft Office Professional Plus 2010

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.

Course Hardware Level


To ensure a satisfactory student experience, Microsoft Learning requires a minimum equipment
configuration for trainer and student computers in all Microsoft Certified Partner for Learning Solutions
(CPLS) classrooms in which Official Microsoft Learning Product courseware is taught.
MCT USE ONLY. STUDENT USE PROHIBITED
vi About This Course

Hardware Level 6+

• Intel Virtualization Technology (Intel VT) or AMD Virtualization (AMD-V) processor


• Dual 120 GB hard disks 7200 RM SATA or better*
• 8GB or higher
• DVD drive
• Network adapter with Internet connectivity
• Super VGA (SVGA) 17-inch monitor
• Microsoft Mouse or compatible pointing device
• Sound card with amplified speakers
*Striped
In addition, the instructor computer must be connected to a projection display device that supports SVGA
1024 x 768 pixels, 16 bit colors.
1-1

Module 1
Overview of HTML and CSS
Contents:
Module Overview 1-2 

Lesson 1: Overview of HTML 1-3 

Lesson 2: Overview of CSS 1-22 


Lesson 3: Creating a Web Application by Using Visual Studio 2012 1-31 

Lab: Exploring the Contoso Conference Application 1-39 

Module Review and Takeaways 1-50 


1-2 Overview
w of HTML and CSS

Modu
ule Ove
erview

Moost modern web


w applicatio ons are built upon a foundaation of HTMLL pages that d describe the co
ontent that
ers read and iinteract with, style sheets to
use o make that content
c visually pleasing, an
nd JavaScript code to
pro
ovide a level of
o interactivityy between use er and page, and
a page and d server. The web
w browser u uses the
HTTML markup aand the style ssheets to rend der this content, and runs the JavaScript code to implement the
be
ehavior of the application. TThis module reviews the baasics of HTML and CSS, and d introduces th
he tools
tha
at this course uses to createe HTML pages and style sh heets.

Ob
bjectives
e, you will be able to:
Aftter completing this module

• w to use HTML elements an


Explain how nd attributes tto lay out a web page

• 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

HTML has bee


H en the publish
hing language
e of the web ssince 1992. In this lesson, yo
ou will learn tthe
f
fundamentalss of HTML, how HTML page es are structurred, and somee of the basic features that can be
a
added to an H
HTML page.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Describe the structure of an HTML p


page.

• Explain basic HTML ele


ements and atttributes.
• Create an
nd correctly m
markup an HTM
ML page conttaining text elements.

• b using image elements, and link pagess together by using anchor


Display graphics in an HTML page by
elements.

• 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.

ery HTML pag


Eve ge has the sam
me basic struccture:

• A DOCTYPEE declaration sstating which version of HT


TML the page
e uses.

• An html secction that con


ntains the follo
owing elemen
nts:

o A head der that contains informatio


on about the page
p for the b
browser. This may include iits primary
language (English, C Chinese, French, and so on),, character sett, associated sstyle sheets an
nd script
files, au
uthor information, and keywwords for search engines.

o A bodyy that contains all the viewaable content o


of the page.
This is true for all
a versions of HTML up to and
a including
g HTML5.

n HTML5 web page should include a DO


An OCTYPE declaration, and a <html>
< eleme
ent that in turrn contains
a<<head> eleme
ent containing
g the title and
d character se
et of the page and a <bodyy> element fo or the
content.

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>

The code examp


ple above use
es the DOCTYP
PE declaration
n for HTML5.

<
<!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.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd>

• Frameset DOCTYPEs, which allow the use of frames in addition to the elements allowed by the
transitional DOCTYPE.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"


"http://www.w3.org/TR/html4/frameset.dtd">

• Strict DOCTYPEs, which do not permit the use of frames or deprecated elements from previous
versions of HTML.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">

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

• A closing taag, </p>, to denote


d nd of the paragraph
the en

Tags and eleme d to interchangeably, although this is inccorrect. An ele


ents are somettimes referred ement
consists of tags and content.

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

Eve ery web pagee requires content: text and


d images. HTM
ML defines maany elements that
t enable yo
ou to
strructure that co
ontent and to
o give it some sematic context.

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.

• <p> identiffies paragraph


hs of text

• <h1>, <h2 2>, <h3>, …, <


<h6> identiffy six levels of heading text. Use <h1> too identify the main
heading of the entire pag eadings of each section in the page, <h3> to
ge, <h2> to iidentify the he
identify the
e sub-sections within those secondary he eadings, and sso on.

It iis important to use the heaading and paragraph tags to


t identify secctions, sub-secctions, and texxt content
in a Web page. Headings and d tags make the content more understan ndable to readders and inde exers, as
we o read on screen.
ell as easier to

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.

• <b> and <i> identify text to be rendered in bold or in italics, respectively.

You can combine and nest the <strong>, <em>, <b>, and <i> elements to indicate different types of
emphasis.

Browsers can render emphasized text in many different ways.

Adding stress to text


<p>
To <strong>emphasize</strong> is to give extra weight to (a communication); <em>"Her
gesture emphasized her words"</em>.
</p>

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

• Ordered lists group sets of items in a 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.

Unordered, ordered, and definition lists


<body>
<p>Here’s a small list of HTML editors</p>
<ul>
<li>Notepad</li>
<li>Textmate</li>
<li>Visual Studio</li>
</ul>
<p>Here’s how to write a Web page</p>
<ol>
<li>Create a new text file</li>
<li>Add some HTML</li>
<li>Save the file to a website</li>
</ol>
<p>Here’s a small list of people in the Internet Hall of Fame and what they did</p>
<dl>
<dt>Sir Tim Berners Lee</dt>
<dd>Invented HTML and wrote WorldWideWeb</dd>
<dt>Linus Torvalds</dt>
1-10 Overview of HTML and CSS

<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.

Writing nested lists


<body>
<ol>
<li>Lesson One: Introduction to HTML
<ol>
<li>The structure of an HTML page</li>
<li>Tags, Elements, Attributes and Content</li>
<li>Text and Images</li>
<li>Forms</li>
</ol>
</li>
<li>Lesson Two: Introduction to CSS</li>
<li>Lesson Three: Using Visual Studio 2012</li>
</ol>
</body>

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

You use the H


Y HTML <img> tag to insert an image into o your web paage. It does noot require an end tag as it
d
does not conttain any conte
ent. In additio
on to the glob
bal attributes, the <img> taag has a numbber of
a
attributes to d
define it:
• The src attribute specifies a URL tha
at identifies th
he location of the image to be displayed

• The alt atttribute identiifies a text alte


ernative for d
display in place
e of the image if the browsser is still
download not display it for some reasson; for example, if the ima
ding it or cann age file is misssing. It
typically describes
d the content of th he image.

• The title attribute iden


ntifies some te d in a tool-tip when a user’ss cursor hovers over the
ext to be used
image
• The longdesc attribute
e identifies an
nother web paage that descrribes the imag
ge in more de
etail

• The heighht and width h attributes sett the dimensio


ons in pixels o
of the box on the web page
e that will
contain th
he image; if thhe dimensions are differentt from those ofo the image, browsers will resize the
image onn the fly to fit the box

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>

Additioonal Reading: With so man ny hardware devices


d – phon nes, tablets, te
elevisions, and
d
monitors – offfering the use
m er a chance to
o browse a weeb page in maany different rresolutions, it has
b
become very important to offer the samme image at diifferent sizes rrather than alwways getting the
b
browser to scaale the picture
e. The problem now is how
w to identify wwhich version of the image
1-12 Overview of HTML and CSS

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.

Anchor tags have the following non-global attributes:

• The href attribute identifies the web page or resource to link to

• 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 hreflang attribute identifies the language of the linked resource

• 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.

Adding hypertext links to your web page


<body>
<ul>
<li><a href=”default.html” alt=”Home Page”>Home</a></li>
<li><a href=”about.html” alt=”About this Web site”>About</a></li>
<li><a href=”essays.html” alt=”A list of my essays”>Essays</a></li>
</ul>
</body>

The href attribute is the most important part of linking one online resource to another. You can use
several different value types:

• A URL in the same folder (for example: about.html)

• A URL relative to the current folder (for example: …/about.html)

• A URL absolute to the server root (for example: /pages/about.html)

• A URL on a different server (for example: http://www.microsoft.com/default.html)


• A fragment identifier or id name preceded by a hash (for example: #section2)

• A combination of URL and fragment identifier (for example: about.html#section2)


Programming in HTTML5 with JavaScrippt and CSS3 1-13
3

G
Gathering
g User Inp
put by Usin
ng Forms in HTML

Many web site


M es require the
e user to inputt information,, such as a use
er name, password, or addrress. Text and
i
images define
e content thatt a user can re m provides a user with a baasic level of in
ead, but a form nteraction
w a site, givving the user an opportunity to provide data that willl be sent to th
with he server for ccollation and
p
processing.

Use the HTMLL <form> ele


U ement to identify an area off your web paage that will aact as an inputt form. This
e
element has tthe following attributes:

• The actioon attribute, w


which identifie
es the URL of the page to w
which the form
m data submittted by the
user will b
be sent for processing.

• 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

• The accep pt-charset atttribute, which


h identifies the character en
ncoding of the data submittted in the
form by tthe user.

• ype attribute,, which identiffies the MIMEE-type used w


The encty when encoding
g the form daata for
submissio
on when the method
m is POS
ST.

• The targeet attribute, w


which identifie
es where the b
browser will display the acttion page; valiid values are
_blank, _parent, _self,, and _top.

Y can add ccontrols and ttext elements to the form e


You element’s content to define
e its layout.

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

text (default) A single-line text box

password A single-line text box where th


he text entered into the box is
1-14 Overview of HTML and CSS

Value Result
replaced by asterisks.

hidden A field not visible to the user

checkbox A checkbox. Provides a yes/no or true/false choice. Use the


selected attribute to indicate if it is checked by default.

radio A radio button control. Use the name attribute to group


several radio button controls together. The form will allow
either none or one of the grouped radio buttons to be
selected.

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.

button A button. This has no default behavior and may be used to


run a script when clicked, for example.

file A file control. Provides a way to submit a file to the server


when the submit button is clicked.

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.

Form Layout Elements


You can use <p> and <div> tags to apply a basic layout to a form. HTML also defines two further tags
that can help to improve a form’s presentation:

• <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

Using a form to obtain the details of a user


<form method="post" action="/registration/new" id="registration-form">
<label for="first-name">First name:</label><br />
<input type="text" id="first-name" name="FirstName"/><br />
<label for="last-name">Last name:</label><br />
<input type="text" id="last-name" name="LastName"/><br />
<label for="email-address">Email address:</label><br />
<input type="email" id="email-address" name="EmailAddress"/><br />
<label for="password">Choose a password:</label><br />
<input type="password" id="password" name="Password"/><br />
<label for="confirm-password">Confirm your password:</label><br />
<input type="password" id="confirm-password" name="ConfirmPassword"/><br />
<label for="website">Website/blog:</label><br />
<input type="url" id="website" name="WebsiteUrl" /><br />
<button type="submit">Register</button>
</form>
1-16 Overview of HTML and CSSS

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.

3. Add the following basic HTML structu


ure to the blan
nk text file.

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-
-8" />
<title>C
Contact Us</
/title>
</head>
<body>
</body>
</html>

Savve the file as E:\Democode


e\ ContactUs.h
html.

Ad
dd Content to the Page

1. Add a level 1 page heading to the <b


body> elemen
nt.

<h1>Contact Contoso C
Conferencing
g</h1>

2. Add the company address by using tw


wo paragraphs and the line
e break element as follows:

<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>

Save the file.


Add a Form with Input Controls

1. Add the following <form> element to the page beneath the text created previously.

<form method="Post" action="support.aspx">


</form>

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>

4. Save the file


e and close Notepad.

ew the Page
Vie

1. dows taskbar, click the File Explorer icon..


In the Wind
2. Browse to tthe folder E:\D
Democode.

3. Double-clicck ContactUs..html to displlay the page in Internet Exp


plorer.

4. In the How do you want to open this ttype of file (.h


html)? dialog box, click Inte
ernet Explorerr.
The page sh
hould look likke this:

FIGURE 1.1: THE CON


NTACTUS PA
AGE
5. Enter some sample data, but do not click Send.

Note: If yo end, Internet Explorer


ou do click Se E will d
display the meessage This page
p can't be
dissplayed. This occurs becau use the URL th
hat is specified
d as the action
n attribute forr the form
(su
upport.aspx) does
d not exist..
Programming in HTML5 with JavaScript and CSS3 1-19
1-20 Overview of HTML and CSSS

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:

• he content part of a <scrip


Write the JaavaScript on tthe page as th pt> element.

<script t
type="text/javascript">
alert('
'I am a line
e of JavaScript');
</script>
>

• Save the JavvaScript in a sseparate file o


on your web site and then rreference it byy using the srrc attribute
of the <script> elementt.

<script t
type="text/javascript" src="alertme
e.js"></script>

• Reference a third-party JJavaScript file on a different web site.

<script t
type="text/javascript"
src="ht
ttp://ajax.c
contoso.com/ajax/jQuery/
/jquery-1.7.2.js">
</script>
>

The <script> ele


ement has thrree attributes::

• The type atttribute, which


h identifies wh
hich script lan
nguage is used
d; the default is text/javasscript.
• The src attrribute, which iidentifies a sccript file for do
ownload; do n
not use src if yyou are writing script
into the conntent part of the
t <script> e element.

• The charset attribute, wh hich identifiess the characte


er encoding (for example, u utf-8, Shift-JIS)) of the
external scrript file; if you are not usingg the src attrib
bute, do not sset the charse
et attribute.

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.

The <noscript> element


<body>
<noscript>This page uses JavaScript. Please enable it in your browser</noscript>

Rest of page

<script src="MyScripts.js"></script>
</body>

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

Whhere HTML de efines the stru


ucture and context of a web
b page, CSS d
defines how it should appeaar in a
bro
owser. In this lesson, you will
w learn the fuundamentals of CSS, how tto create somee basic styles, and how
to attach these styles to elem
ments of an HTTML page.

Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:

• Explain basic CSS syntax

• ow CSS selecto
Describe ho ors work
• Describe ho
ow CSS styles inherit and caascade

• Attach CSS to an HTML p


page
Programming in HTTML5 with JavaScrippt and CSS3 1-23
3

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;
}

T example shows the fou


This ur parts of eve
ery CSS rule:
• A selectoor defines the element or se et of elements to target. Thhe styling specified by the CSS
C rules
associatedd with this sellector is applied to all elem
ments on the web
w page thatt match this se elector. A CSSS
selector can
c specify the e element nam me itself, or th
he attribute o
of an element.
• A pair of curly braces e
encloses the rules for the se
elected eleme
ents. A rule de
efines how to render an
element; it contains a property-valu
p ue pair suffixed
d by a semi-colon.

• A properrty identifies tthe visual aspe


ect of the elem
ment to change.
• A values variable speccifies the stylin
ng to apply too the propertyy. Values can vvary dependinng on the
property. They might bbe color name es, size values in percentages, pixels, ems, or points, o
or the name
of a font, to name thre
ee possibilitiess.
You can also add
Y a commen nts to your styyle sheets by u
using /* */ de
elimiters. The browser
b will ig
gnore
c
comments. Coomments can span one or more lines. Yo ou can write tthem outside of or within a CSS rule.

All CSS rules h


A have the same
e basic syntaxx. Beyond thatt, the first key to CSS is to know
k the propperties to
a
apply to sets of
o elements. T
This example d demonstratess the use of so ome text-speccific properties.
1-24 Overview of HTML and CSS

Some simple CSS rules


/* Targets level 1 headings and renders them as large pink text using the Segoe UI font
*/
h1 {
font-size: 42px;
color: pink;
font-family: 'Segoe UI';
}
/* Targets emphasized text, rendering it as italicized on a yellow background */
em {
background-color: yellow; /* Yellow is a good highlight color */
font-style: italic;
}

In the example above, the two rules translate as follows:

• 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

CSS selectors specify the co


C ontent to be sstyled by using
g the associatted set of rule
es, and undersstanding how
C selectors work is the ke
CSS ey to defining
g reusable and d extensible sttyle sheets.

The CSS speciification proviides many diffferent ways to


T o select the element or set of elements in a web page
e
he following list summarize
t which presentation ruless will apply. Th
to es the basic se
electors and the set of
e
elements thatt they identifyy.

• 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.

• The classs selector, ide entified by a p


period, returns the set of all elements in the page wheere the class
attribute is set to the specified valuee. For examplee, .myClass {} returns the se
et of elementss where the
class attrribute is set to
o "myClass".

• The id se elector, identiified by a hash


h, returns the set of all elem
ments in the page
p where th
he id attribute
e
is set to the specified vvalue. For exam
mple, #thisId {} returns the set of any ele
ements wheree the id
attribute is set to "thisIId".

The class selecctor may return a set contaaining differen


T nt types of HT
TML elementss—for example, <p>,
<section>, an nd <h3>—if th hey all have the same classs attribute valu
ue. The same is true of the id selector,
a
although this selector shou uld only returnn a single elem
ment because ute in a page should be
e the id attribu
u
unique (this iss not enforced
d).

SStyle sheets are often writteen with the leeast specific se


electors first aand the most specific
s selecttors last.
E
Element selecctors are the le
east specific, ffollowed by cllass and id sellectors, and th
hen combinattions of the
t
three.

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:

h2.blue Returns any <h2> elements of class "blue"

h2#blue Returns any <h2> elements with id "blue"

section, h2 Returns any <h2> and any <section> elements

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

The Wildcard Selector


The wildcard selector * returns the set of all the elements in a document. This selector is rarely used by
itself, but it can be useful in combination with other elements. For example, the following rule returns a
set of all elements within an <aside> element and makes them slightly fainter.

aside * { opacity : 0.6; }

The Attribute Selector


You can further refine any of the selectors already described by inspecting an element for the declaration
of an attribute and its value. The attribute selector is contained in a pair of square brackets appended to a
selector and can have any of the following forms:
Programming in HTML5 with JavaScript and CSS3 1-27

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

How HTMLL Inheritan


nce and Caascading Styles Affect Styling
g

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;
}

If inheritance didn't exist, you


u would have to set this pro
operty on eveery single type
e of element ccontaining
texxt content. Yo
ou might end up writing ma any repeatingg styles as shown in the following code eexample,
wh hich can be difficult to main ould probably also be looking for an alte
ntain. You wo ernative to CSSS.

h1, h2, h3, h4, h5, h6 {


h
font-family: Candara;
}
p {
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.

h2 { font-weight : bold !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:

• Write rules specific to an


n element with
hin its style atttribute.

<p style=
="font-family : Candara; font-size:
: 12px; "> … </p>

• Write a set of rules specific to a page w


within its <he
ead> elementt by using <styyle> tags.

<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 <link> elem


ment has four CSS-relevant attributes:

• The href atttribute speciffies a URL thatt identifies the


e location of tthe style sheet file.

• The rel attrribute indicate


es the type of document th
he <link> elem
ment is referen
ncing; set thiss to style
sheet when n linking to styyle sheets.

• The media attribute indiicates the type e of device targeted by the


e style sheet; p
possible value
es include
speech for speech synthesizers, print for printers, h handheld for mobile devicces and all (the default),
indicating tthe style sheett is all purpose

• 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

The type and media


m attribute
es have the saame function for
f the <style> element as their namesaakes for the
<liink> element.
Programming in HTTML5 with JavaScrippt and CSS3 1-31
1

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.

This lesson inttroduces Visual Studio 2012 and the sup


T pport it includ
des for buildin
ng web applica
ations. This
l
lesson also exxamines the F1
12 Developer Tools for Inte
ernet Explorerr.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• g Visual Studio 2012


Open, insspect and run a web application by using

• 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:

• b applications using HTML5


Create web 5, CSS3, and JaavaScript.

Vissual Studio 20012 provides a collection off project temp


plates to get yyou started buuilding web applications.
If yyou are buildiing applications by using H
HTML5 and JavvaScript only, the most app propriate templates are
the e ASP.NET Emmpty Web Site e and ASP.NETT Empty Web Application templates. You u can structurre your web
appplication to o
organize the content by cre nal folders insside the proje
eating addition ect.

• 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:

• An HTML editor updated


d to recognize
e HTML5 tags and attribute
es.

• A new JavaScript editor w


with IntelliSen
nse support.

• or updated to support CSS3


A CSS edito 3 properties and value type
es.

• A new CSS color picker.

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

Note: Thiss demonstratiion assumes tthat you have completed th emonstration,


he previous de
and that the file
e ContactUs.h
html is availab
ble in the E:\D
Democode fo
older.

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.

3. In the New Web Site dialog box, click ASP.NET Emp


pty 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.

5. On the File menu, click S


Save DemoW
WebSite.
dd and Edit Filles in the Projject
Ad

1. In Visual Stu
udio, click Sollution Explorrer.

2. In the Soluttion Explorer window,


w rightt-click the Dem
moWebSite project.
p
3. In the conte
ext menu, poiint to Add and then click E
Existing Item..

4. In the Add Existing Item


m dialog box, browse to E:\\Democode, click ContacttUs.html, and
d then click
Add.
Programming in HTML5 with JavaScript and CSS3 1-35

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

7. Change the name of the folder to styles.

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.

11. In the Solution Explorer window, double-click ContactUs.html.


12. Add the following markup shown in bold to the <head> element of the page.

<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.

13. On the File menu, click Save All.

Run the Web Application


1. On the Debug menu, click Start Debugging.

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.

5. Leave Internet Explorer running and return to Visual Studio 2012.

Modify the Live Application

1. In the ContactUs.html file, make the following modifications:

a. Change <strong>Name</strong> to <strong>Full name</strong>

b. Change Telephone to Telephone number

2. In the ContactUsStyles.css file, add the following style:

h1 {
font-family: 'Copperplate Gothic';
color: red;
}

3. On the File menu, click Save All.

4. Return to Internet Explorer and press F5 to refresh the display.

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.

6. Return to Visual Studio 2012.

7. On the Debug menu, click Stop Debugging.


Programming in HTTML5 with JavaScrippt and CSS3 1-37
7

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.

• View a paage as if it were being view


wed in Internett Explorer versions 7, 8, 9, o
or 10

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 Find menu enable


es you to selecct the HTML m
markup for an
n element by clicking
c on it.

• The Disab
ble menu enaables you to to
oggle Interne
et Explorer's su
upport for blo
ocking popups, script and
CSS.

• The Vieww menu enable es you to togg e elements on the page


gle the display of information about the
such as link paths and tab indexes; tthis informatio
on overlays th
he page.
1-38 Overview of HTML 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.

Beneath the menu bar, there are six tabs:


• The HTML tab has two panes. The left shows a tree-view of the HTML elements in the current page:
its Document Object Model. Clicking on any element in the tree-view populates the right pane with
its CSS styles and attribute values. You can also use this pane to edit the HTML content of a 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

Lab: Exploriing the Contoso Con


nference
e Application

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.

You are a devveloper that crreates web sittes by using H


Y HTML, CSS, and JavaScript, and
a you have e been given
a
access to the code for the web
w site for th erence. You d
he latest confe decide to take
e a look at thiss web
a
application to
o see how it w
works, and how w the develop per has used V
Visual Studio 2
2012 to create e it.

O
Objectives
A
After completting this lab, you
y will be able to:

• Describe the structure of the Contosso Conference


e web applica
ation.

• Use Visuaal Studio 2012


2 to examine the
t structure o
of a web appllication, run a web applicattion, and
modify a web application.
E
Estimated Tim
me: 30 minutes

• Virtual Machines: 2048


80A-SEA-DEV1
11-01, MSL-TMG1

• User Nam
me: Student
• Password
d: Pa$$w0rd
1-40 Overview of HTML and CSS

Exercise 1: Exploring the Contoso Conference Application


Scenario
In this exercise, you will run the Contoso Conference web application and examine each of the functions it
provides.

The Contoso Conference web application contains the following pages:

• 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.

The main tasks for this exercise are as follows:

1. Start the web application and view the Home page

2. View the About and Schedule pages

3. View the Register page and register as a new attendee


4. View the Location page

5. Submit a question and provide conference feedback

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.

3. Start Visual Studio.


4. Open the ContosoConf solution in the E:\Labfiles\Starter folder

5. Run the application.

The Home page is displayed in Internet Explorer, like this:


Programming in HTTML5 with JavaScrippt and CSS3 1-41
1

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

FIGURE 1.4: THE ABO


OUT PAGE
Nootice that wheen you click ann item in the menu bar, the
e style of the item changess; it is displaye
ed with a
rib
bbon effect. Th
his feature is implemented
i by using CSS.

The other styling features, inccluding the laarge drop-cap


pital "S" at the start of the fiirst paragraph
h, the
column layout, and the quota ation in the th
hird column, aare also imple
emented by ussing CSS.

2. Move to the
e Schedule page.
p
The Scheduule page lookks like this:

FIGURE 1.5: THE SCH


HEDULE PAGE
E
The list of sessio
ons is held in a database that is accessed d by using a web
w service. Thhis page uses JavaScript
code to connectt to the web sservice, retrievve the list of sessions,
s and d
dynamically p
populate the b
body of this
page with the se ession information.
Programming in HTTML5 with JavaScrippt and CSS3 1-43
3

A user can sellect a session that is of inte


erest and clickk the star icon.. When this ha
appens, notice e that the
s changes ccolor and thatt number nexxt to the star in
star ncreases. This number indiccates how ma any attendees
h
have expresse
ed an interest in this session n; to get a good seat, the uuser may need d to arrive earrly for popularr
s
sessions. The user can clickk the star againn to deselect it, and the nuumber of interrested attende ees drops by
o
one.
The functionaality is implem
T mented by a co ombination off CSS and JavaScript code that
t sends information to
a
another web service
s about the sessions that
t a user selects.

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.

T confirmattion page looks like this:


The
1-44 Overview of HTML and CSSS

FIGURE 1.7: THE REG


GISTRATION CONFIRMAT
TION PAGE

X Task 4: View the Loca


ation page
1. Move to the
e Location pa
age.
The Locatio
on page lookss like this:

FIGURE 1.8: THE LOC


CATION PAGE
2. If the messaage localhostt wants to tra
ack your phy
ysical location
n appears in tthe Internet Exxplorer
message baar, click Allow
w once.
The page displaays informatio
on about your current locattion (the distance from the conference venue) by
usiing the Geolo
ocation API in JavaScript.
Programming in HTTML5 with JavaScrippt and CSS3 1-45
5

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:

FIGURE 1.10: THE FEEDBACK PAG


GE.
The Feedback p edback about a session by sselecting a staar rating
page enables an attendee tto provide fee
and by providin
ng additional comments.
c

The star rating is implemente d HTML5


ed by using a combination of JavaScript code and CSSS styles behind
inp
put fields.

6. Provide a raating for a sesssion.

otice that whe


No en you send th
he feedback, tthe form flies off the screen
n to indicate that
t the feedb
back has
be
een posted. Th
his animation is performed by using CSS.

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

Exercise 2: Examining and Modifying the Contoso Conference Application


Scenario
In this exercise, you will examine the Visual Studio 2012 project for the Contoso Conference application.
You will see how the project is structured, and how the files and scripts for the project are organized into
folders. You will then run the application again, make some modifications to the HTML markup and CSS,
and view the results.

The main tasks for this exercise are as follows:


1. Explore the web pages for the application by using Visual Studio 2012

2. Explore the structure of the project

3. Run the application and make live modifications

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

The venue map is drawn by using Scalable Vector Graphics.

6. View the live.htm file.


This file contains a form that enables a user to submit questions.
Questions are posted to a server listening on a web socket.
Questions posted by other users are received by using a web socket, and then added to the list on the
page.
The JavaScript code that implements the web socket code is located in the live.js file.

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.

X Task 2: Explore the structure of the project


1. The files for the project are organized into the following folders. Examine the contents of each folder
in turn:
o images. This folder contains photographs of speakers and logos of conference sponsors.

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.

X Task 3: Run the application and make live modifications


1. Build and run the web application without debugging, and display the Home page.
2. Leave the application running and return to Visual Studio 2012.

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.

nally, you have


Fin e seen how to o use Visual Sttudio 2012 to
o create and ru un a web application, and how
h to use
the
e F12 Develop per Tools in In
nternet Explorrer to examinee a live application.
Question: What
W are the four elements that define tthe basic structure of an HT
TML page?

Test Your Know


wledge

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.

Include all rules for each element in the <style


e> attribute o
of the elementt.

Include the rules for each page in


n a <style> ellement in the <head> elem
ment.

Write the rules for tthe whole site


e in one or mo
ore style sheetts and referen
nce them
ng a <style> element in the <head> ele
by usin ement of eachh page.

Write the rules for tthe whole site


e in one or mo
ore style sheetts and referen
nce them
ng a <link> e
by usin element in the e <head> elemment of each page.

Write the rules for tthe whole site


e in one or mo
ore style sheetts and referen
nce them
Programming in HTML5 with JavaScript and CSS3 1-51

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 

Lesson 1: Creating an HTML5 Page 2-3 

Lesson 2: Styling an HTML5 Page 2-13 


Lab: Creating and Styling HTML5 Pages 2-26 

Module Review and Takeaways 2-33 


2-2 Creating and Styling HTML PPages

Modu
ule Ove
erview

The technologie es forming thee basis of all w


web applicatioons—HTML, CSS,C and JavaSScript—have b been
avaailable for maany years, but the purpose and sophistication of web applications h have changed d
sig TML5 is the firrst major revission of HTML in 10 years, and it providess a highly suitable means
gnificantly. HT
of presenting co ontent for trad unning on handheld mobille devices,
ditional web aapplications, aapplications ru
and also on the Windows 8 p platform.

present content by using


This module introduces HTML5, describes its new features, demonstrrates how to p
the
e new feature
es in HTML5, aand how to styyle this content by using CSS.

Ob
bjectives
e, you will be able to:
Aftter completing this module

• n how to use new HTML5 e


Describe the purpose of and new features in HTMLL5, and explain elements to
eb page.
lay out a we

• 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:

• Describe the new featu


ures of HTML5
5.

• 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.

• Add new feeatures that re


eflect how the
e web is now u
used. For exam
mple, HTML5 supports form
m validation
and video.

• w every browsser should beh


Specify how have when wo orking with HT
TML. All HTM
ML implementaations can
be interope
erable. This be
ehavior includ
des defining how to handle errors.
• Be universaally accessible.. Features sho
ould work acro uage, and for tthe
oss all devicess, in any langu
disabled.

Referencee Links: You ccan see these aims explaine


ed in full at
htttp://go.microssoft.com/fwlin
nk/?LinkID=2667713

The most obvious new featurre in HTML5 iss the DOCTYP


PE declaration
n, which descrribes which ve
ersion of
HT
TML a page usses.

Note: The
e DOCTYPE de
eclaration wass described in
n module 1.

HT
TML5 defines many other n
new features, including:
i

• New elements that impro


ove the semantic structure of a document.

• New form ccontrols and built-in


b validattion.

• Native audiio and video ssupport, so ussers do not ha


ave to rely on browser plug
g-ins.
Programming in HTML5 with JavaScript and CSS3 2-5

• 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 for uploading files to a web server.

• Support for dragging and dropping elements on the page.

• 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

Document Structure in HTML5

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.

ne of the most common tassks in a page is to identify d


On different areas of the document: the navvigation
bar, the header,, the footer, and so on. In H
HTML4, you used the id atttribute. For exxample:

<ul id="navigation"> .. </ul>


<
<
<div id="footer> .. </di
iv>

Whhile this appro


oach is convenient, it does not convey th
he semantic mmeaning of the different are
eas. HTML5
pro
ovides a much h richer semantic structure for documennts, including:

• The <sectioon> element, which identiffies component pieces of ccontent on a page.


p For exammple, the
ingredients and the meth
hod in a recip
pe displayed b
by a page could be two sep parate sections.
• The <header> element, which identiffies the conten
nt in the head
der of the pag
ge. For examp
ple, a
company website
w might include its log
go, name, andd motto in the
e <header>.

• The <foote er> element, which


w identifies the conten
nt in the foote
er of the page
e. For example
e, links to
site maps, p
privacy statem
ments, and terms and condiitions are ofteen included in the <footer>.

• 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.

• The <articlle> element, which


w e pieces of content that wo
identifies standalone ould make sen nse outside
ext of the current page. For example, a b
of the conte blog post, a re
ecipe, or a cattalog entry.
• The <aside e> element, wwhich identifie
es content rela
ated to an <arrticle> but w
which isn't partt of its main
flow. For exxample, you might
m use <aside> to identtify quotes or sidebar conte ent.

The following markup


m examp
ple shows one
e way to markk up an HTML5
5 document b
by using the new
n
strructural eleme
ents.

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

HTTML5 supportts the header, paragraph, and emphasis e


elements used
d in the previo
ous version off HTML.
HTTML5 also deffines a numbe
er of new elem
ments to impro
ove the semantic context of
o the docume ent,
inccluding:
• up> element,, which indicaates that its co
The <hgrou ontents should
d be treated as
a a single heaading.

<hgroup>
<h1>My Recipes</h11>
<h2>Greeat to eat, easy to make</h2>
</hgroup>>

• The <time> > element, wh hich enables yyou to define an unambigu


uous time, durration, or period that is
both human and machin The datetime attribute contains the ISO standard reprresentation
ne readable. T
of the conte
ents of an element.

<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>This text should


d be <mark>no
oted for fut
ture use</ma
ark> rather than
<em>empha
asized</em>.</p>

• The <smalll> element, which


w identifie
es that its conttents should b
be treated as sside comments, such as
small print or author attrributions.

<p>Heat y
your beans f
for five minutes. <small
l>Or until t
they are hot enough for
you.</sma
all></p>

• The <figure> element, w which is typica


ally used to id
dentify an ima
age, video, or code listing and
a its
associated descriptive
d co
ontent and othher elements. If the content needs a capption, you can nest the
<figcaption> element in nside the <fig
gure> elemen nt.

<figure>
Programming in HTML5 with JavaScript and CSS3 2-9

<img src="plateofbeans.jpg" alt="A Plate of beans on toast" />


<figcaption>A wonderful plate of beans in five minutes flat</figcaption>
</figure>

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.

4. In Solution Explorer, expand the E:\...\\DemoWebS


Site web appliication, and th
hen double-cllick
ContactUs..html.
5. In the ConttactUs.html ffile, enclose th
he entire contents of the <b
body> eleme
ent in an <artticle>
element as shown in bold d in the follow
wing code exaample:

<!DOCTYPE HTML>
<html lang="en">
...
</head>
<body>
<article
e>
...
</article>
</body>
</html>

6. Within the <article> ele


ement, enclosee the first thre
ee <p> elemeents containin
ng the company name,
address, and contact email in a <sectiion> elementt, as shown in bold in the fo
ollowing code
e example:

...
<h1>Contact Contoso C
Conferencing
g</h1>
<section>
Programming in HTML5 with JavaScript and CSS3 2-11

<p>Contoso Conferencing Ltd.</p>


<p>123 South Street<br />
Somewhere<br />
Over There<br />
<em>USA</em></p>
<p>
<a href="mailto:contact@contoso.com">contact@contoso.com</a>
</p>
</section>
<p>
If you would like to contact Contoso Conferencing ...
</p>
...

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>
...

8. On the File menu, click Save All.

Add a Header and a Footer to the Page

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>

4. On the File menu, click Save All.


View the Structure of the Page by Using the F12 Developer Tools

1. On the Debug menu, click Start Without Debugging.

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.

4. In the F12 window, click the HTML tab.


5. Expand the <html> element.

6. Expand the <body> element.

7. Expand the <article> element and verify that it contains a <header> element and two <section>
elements.

8. Expand the <header> element.

9. Expand the <h1> element.


10. Click each element, and verify that Internet Explorer surrounds each element on the page with a box
as it is selected in the F12 window.

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.

3. Verify that Internet Explorer displays the modified text.


4. Press F12 to close the F12 window.

5. Close Internet Explorer, and then close Visual Studio 2012.


Programming in HTTML5 with JavaScrippt and CSS3 2-13
3

Lesson 2
Stylin
ng an H
HTML5 Page

After you havve defined the


A e structure andd set the conttent of a web page, your ne ext task is to aapply some
p
presentation r
rules to it by u
using CSS. In tthis lesson, yo
ou will learn about the coree CSS propertiies that you
c use to styyle the text and background
can d of a page. Y You'll also learrn how to use the CSS box model to
p
position blockk-level elemen nts on a pagee.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to

• Use CSS ttext styles to sset the fonts u


used in a page ext properties.
e and other te

• Explain ho
ow to use the
e CSS box mod
del to position
n elements on
n a page.

• Use CSS tto set the background for tthe elements on


o a page.
2-14 Creatingg and Styling HTML Pages

Understand
ding CSS Text
T Styless

Hoowever good tthe layout of a website, it ccan be nullifie


ed if you write
e poor content or present itt badly. If
content is the fo
oundation of the web, then n typography is the foundation of web d design, and so o the first
sett of CSS prope
erties that you
u should learnn are those that concern th he way in whicch text is displlayed.

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;

• The font-siize property, w which sets the


e height of the font. You caan set the font-size value to o an
absolute vaalue in pixels ((for on-screenn display), in p
points (for prin
nting), or to a value relative
e to the
ment’s font-sizze (in percent)), or relative to the base font size of the page (in ems). The
parent elem
following coode shows some examples:

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 */

• The font-sttyle property,, which enable


es you to sele
ect a normal (vvertical), italic, or oblique vversion of
the font to be displayed, as shown in tthe following example:

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:

p { font : bold 16px/1.5 "Arial"; }


/* The above is a shorthand for the following rules */
p {
font-weight: bold;
font-size: 16px;
line-height : 1.5em;
font-family: Arial;
}

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 following color values are all equivalent. */


color : olive;
color : #808000;
color : rgb(128, 128, 0);

• 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

To determine the layout off an HTML pag


T ge, browsers ttreat each ele
ement in the page
p as a set o
of four nested
d
b
boxes. The CSSS box model enables you tto specify the size of each b
box, and so m
modify the layo
out of each
e
element on thhe page.
T box mode
The el places conttent inside fou
ur boxes: Content, Padding
g, Border, and Margin.

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.

Around the padding box iss the border b


A box, which can n also act as a visible line aaround the content and
p
padding. Use the border p
property to sett its width, color, and style..

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

Using the box model properties


h2.highlight {
height : 100px;
width : 500px;
padding : 10px;
border : 2px dotted blue;
margin : 25px 0 25px 0; /* Could also be written 25px 0 */
}

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

Sttyling Backgroundss in CSS

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.

• The backgrround-image e property, wh


hich enables you
y to specify the URL of an n image to usse as a
background
d for the seleccted elementss. You may use
e a relative orr an absolute URL.

backgroun
nd-image:url('pattern.jpg');

• The backgrround-size prroperty, which h enables youu to set the he


eight and widtth of the backkground
or as percentages of the height and widtth of the specified
image. Use values specifiied in pixels o
element.

backgroun
nd-size: 40p
px 60px; /* 40px wide, 60px high *
*/

• The backgrround-color property, which enables yo ou to set the ccolor of an ele


ement's backg
ground. You
can specify the color as aan RGB (red-g e of the 147 predefined color names
green-blue) vaalue or as one
in the HTML and CSS spe ecification.

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 *
*/

• The backgrround-origin n property, wh


hich enables yyou to set which of the box model boxess the
backgroundd-position sho
ould be relativve to. Possible
e values are co
ontent-box ((the default), p
padding-
box, and bo
order-box.
Programming in HTML5 with JavaScript and CSS3 2-21

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.

background-repeat : repeat-x; /* Repeat background image only horizontally */


background-repeat : no-repeat; /* Don't repeat the image */

• 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:

article { background : transparent repeat-x url('fluffycat.jpg'); }


/* The above is a shorthand for the following rules */
article {
background-color : transparent;
background-repeat : repeat-x;
background-image : url('fluffycat.jpg');
}
2-22 Creatingg and Styling HTML Pages

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.

4. In Solution Explorer, expand the E:\...\\DemoWebS


Site web appliication, and th
hen expand th
he styles
folder.

5. Double-clicck ContactUsS
Styles.css

6. Review the existing ruless for the body


y and h1 elem
ments.

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

font-family: 'Copperplate Gothic';


color: red;
}

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;
}

10. Add the following empty rule:

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.

18. Click OK.

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

21. On the File menu, click S


Save All.

Usse the F12 Devveloper Tools to Inspect Styyles

1. In Solution Explorer, dou


uble-click Con
ntactUs.html..

2. On the Deb
bug menu, click Start With
hout Debugg
ging.

3. In Internet Explorer, if the message Inttranet settings are turned o


off by default appears, clickk Don’t
show this message
m again n.

4. Verify that tthe new styless have been aapplied to the page.
The ContacctUs page should look like tthis:

FIGURE 2.2: THE CON


NTACTUS PA
AGE WITH STY
YLING
5. In Internet Explorer, presss F12.
6. In the F12 w
window, with the HTML tab selected, do
ouble-click the
e <html> ele
ement to expa
and it.

7. Click the <b


body> eleme
ent.

8. In the right pane, verify tthat the follow


wing the CSS rule appears:

font-family: "Segoe U
UI", Helvetica, Arial, sans-serif;

9. In this rule, select the texxt "Segoe UI"".

10
0. Change the
e value to read
d "Times New
w Roman" an
nd press ENTE
ER.

11. Verify that Internet Explo


orer reflects th
his change to the font on th
he page.
Programming in HTML5 with JavaScript and CSS3 2-25

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;

14. Press F12 to close the F12 window.

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.

Yoou decide to sttart by buildin


ng a prototyp
pe website connsisting of a H
Home page th hat acts as a laanding
page for conference attendee es, and an Ab
bout page thatt describes the purpose of the conferencce. In later
lab
bs you will enh
hance these pages
p and addd further page
es that enablee attendees to
o register for tthe
conference, andd that provide part of the conference.
e information about the sesssions schedulled to run as p

Ob
bjectives
Aftter completing this lab, you
u will be able to:

• ML5 pages
Create HTM

• Style HTMLL5 elements


Esttimated Time:: 45 minutes

• Virtual Macchines: 20480A


A-SEA-DEV11
1-02, MSL-TMG1

• User Name: Student


• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 2-27

Exercise 1: Creating HTML5 Pages


Scenario
In this exercise, you will begin to create the ContosoConf website.

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.

The main tasks for this exercise are as follows:


1. Create a new ASP.NET web application

2. Add the Home page

3. Add images to the Home Page


4. Add the About page

5. Add navigation links

6. Run the web application

X Task 1: Create a new ASP.NET web application


1. Start the MSL-TMG1 virtual machine if it is not already running.

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.

X Task 2: Add the Home page


1. Add a new HTML page, named index.htm to the ContosoConf project.

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.

FIGURE 2.3: THE LAY


YOUT OF THE
E HOME 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

T following image showss how the pag


The ge should app
pear:

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.

• Add an appropriate tittle to the page


e.

• 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.

FIGURE 2.5: THE LAY


YOUT OF THE
E HOME PAG
GE.

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.

2. Verify that tthe correct te


ext and images are displaye
ed.
3. Verify that tthe navigation he correct pag
n links load th ges.

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

Exercise 2: Styling HTML pages


Scenario
In this exercise, you will add styling to the Home and About pages.

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.

The main tasks for this exercise are as follows:


1. Create a new style sheet

2. Add CSS rules to style the pages

3. Run the web application

X Task 1: Create a new style sheet


1. Add a folder named styles to the ContosoConf project.

2. Add a style sheet named site.css to the styles folder.

3. Add a link to the site.css stylesheet from the index.htm and about.htm HTML5 pages

X Task 2: Add CSS rules to style the pages


1. Add CSS rules to the stylesheet to style the <html>, <body>, <nav>, and <h1> elements in the
Home page and the About page. The same styling rules should apply to both pages.
The styled Home page should look similar to this:

FIGURE 2.6: THE STYLED HOME PAGE


• The background color is #EAEEFA.

• The font is Calibri.

• 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

• Use the Inteernet Explorerr F12 develop


per tools to exxperiment with
h the CSS rule
es until you acchieve the
correct styliing

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

FIGURE 2.7: THE STY


YLED ABOUT PAGE

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.

You have also


Y o learned morre about using
g CSS to style text and backkground elem
ments in a web
b page. You
l
learned aboutt the CSS box model, and h
how to apply sstyling to elem
ments based o
on their marg
gin, border,
p
padding, and content.

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?

Select the correct answerr.

Marrgin

Content

Bord
der

Style
e

Padd
ding
 
3-1

Module 3
Introduction to JavaScript
Contents:
Module Overview 3-2 

Lesson 1: Overview of JavaScript 3-3 

Lesson 2: Introduction to the Document Object Model 3-21 


Lesson 3: Introduction to jQuery 3-30 

Lab: Displaying Data and Handling Events by Using JavaScript. 3-41 

Module Review and Takeaways 3-47 


3-2 Introducttion to JavaScript

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.

This module introduces JavaSScript program mming and th


he DOM. It alsso briefly desccribes jQuery, a powerful
op
pen source JavvaScript libraryy that makes web program
mming in JavaSScript easier.

Ob
bjectives
Aftter completing this module
e, you will be able to:

• Describe baasic JavaScriptt syntax.


• Write JavaSScript code tha
at uses the DO
OM to alter an
nd retrieve inffo from a web
b page.

• Use jQuery to simplify many


m common
n JavaScript prrogramming ttasks.
Programming in HTML5 with JavaScrript and CSS3 3-3
3

Lesson 1
Overrview of JavaScript

There are man


T ny programm ming language es in common use, but JavaaScript is by fa ar the most coommon
p
programming g language used for adding g functionalityy to web page
es. In this lesso
on, you will le
earn about the
e
s
syntax of JavaaScript to enab
ble you to staart writing cod
de for your ow
wn web pagess and to understand how
J
JavaScript codde written by other develop pers works.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Explain th
he purpose off JavaScript.

• Describe the basic synttax of stateme


ents and comments in JavaaScript.

• Declare vvariables and w


write expressions by using JJavaScript operators.

• Create an
nd call JavaScrript functions..

• Use conditional statem


ments to contrrol execution fflow.

• Use loop statements to


o implement repeated
r operations.

• Use JavaSScript objects in your code.

• Use JavaSScript Object Notation


N ON) syntax to define an arraay of objects.
(JSO
3-4 Introducttion to JavaScript

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.

At its heart, JavaaScript is a scrripting engine


e with the sam
me basic featu
ures as any oth
her programm
ming
lan
nguage. It pro ovides:

• Variables ffor storing info


ormation.

• Operators for performin


ng calculations and comparrisons.

• Functions ffor grouping statements in


nto reusable chunks.

• Conditional statements aand loop consstructs to conttrol program flow.

• The ability to
t create obje
ects with prop
perties, metho
ods, and even
nts.

Byy itself, JavaScrript cannot do


o much more than perform
m calculations and manipula
ate text, but in
n
combination witth the DOM tthat all browse ers implement you can do far more. For example, you u can use
JavvaScript code to:

• 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.

• React to events, such as a mouse clickking a button.


• e contents of a form before
Validate the e they are sen
nt to the web server.

• 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

eclaring variables, and adding commentts. Any code


JavvaScript has a simple syntaxx for writing sstatements, de
you write must adhere to thiss 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.

Statements and comments


<script type="text/javascript">
document.write("I'm learning JavaScript"); // display a message to the user
/* You can use a multi-line comment
to add more information */
alert("I'm learning JavaScript too!");
</script>
3-8 Introducttion to JavaScript

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:

1. Give it a name and a valu


ue.

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).

var code = "Spang";

There are two im


mportant rule
es for naming variables in Ja
avaScript:

1. Variable names must beg


gin with a lettter or the und
derscore chara
acter.

2. Variable names are case sensitive.

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:

1. String: Anyy set of characcters (alphanu umeric and pu unctuation) en


nclosed in dou
uble quotes. To
T include
special charracters such as ",´, ;, \, and & in your string, escape them with a bacckslash. Also use
u a
backslash too split a string
g over two or more lines.

var simpl
le = "Green Eggs and Ham
m";
Programming in HTML5 with JavaScript and CSS3 3-9

var escaped = "\"Green Eggs \& Ham \"";


var verylong = "Cracked, fried, overripe ovoids and \
porcine strips cooked medium well and allowed to cool";

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.

var answer = 42;


var actuallyAString = "42"; // not treated as a number

3. Boolean: A Boolean value: true or false.

var canYouReadThis = true;

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:

var data = 99;


...
if (typeof data == "number") {
// data is numeric
}

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:

4. Arithmetic operators indicate a mathematical function to be performed on values/variables:


+ (addition)

- (subtraction)

* (multiplication)
/ (division)

% (modulus)

++ (increment)

-- (decrement)

5. Assignment operators assign values to JavaScript variables:

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.

== (is equal to)


!= (is not equal to)

> (is greater than)

< (is less than)


>= (is greater than or equal to)

<= (is less than or equal to)

The second set of two comparison operators does not convert the two values/variables to the same type
before comparison.

=== (is equal in value and in type)

!== (is not equal in value or in type)


7. Boolean operators are used to perform Boolean operations.

x && y returns true if x and y are both true, false otherwise.

x ?? y returns true if either x or y or both are true, false otherwise.

!x returns true if x is false, false otherwise.

8. The ternary conditional operator:

?: 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.

9. The string operator:

+ concatenates two strings. For example, "Bo" + "om" returns "Boom".


There are a number of issues to be aware of with respect to JavaScript operators and how they convert
values\variables between types as the JavaScript interpreter executes expressions.

• If you add a number and a string, the result will be a string!

x=10 + 10; // x is set to the number 20;


y="10"+10; // y is set to the string "1010";
z="Ten"+10; // x is set to the string "Ten10";

• 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:

• The functtion keyword


d indicates thiss is the start o
of a function d
definition.
• The functtion name. Yo
ou use this na
ame to run the
e function. It is case-sensitiive

• 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 set of JavaScript stattements enclo


osed in a pair o
of curly brace
es. These state
ements run wh
hen the
function iis invoked.
A function usees the argume
ents like variaables; it can re
ead their value
es and modifyy them, but th
hey only exist
i
inside the fun
nction.

Note: Function argum ments are opttional. If you d


don't specify any
a argumentts, you can stiill
p
pass paramete ers into a funcction. The arg
guments are aavailable in an
n array called arguments.
a Y
You
c access the
can e first argumeent by using thhe expression
n arguments[0], the second d argument b
by
u
using the expression argum ments[1], and d so on. This m
mechanism gives you a wayy to define
m
methods that can take a vaariable numbe er of parameteers. You can ffind out how mmany parameeters
w
were passed in by querying g the value off arguments.llength.
3-12 Introduction to JavaScript

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.

Creating and calling a function


function CalculateBill(numberOfNightsStay, nightlyRate, extras) {
return (numberOfNightsStay * nightlyrate) + extras;
}

// elsewhere in the script
var TotalAmountOwed = CalculateBill(10, 100, 50);

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

Conditional sttatements enaable you to m


C make decisionss in your JavaSScript code an nd execute diffferent
s
statements deepending on wwhether a Booolean conditio
on is true or faalse. There are
e two commo on types of
c
conditional sttatements:
1
1. An if statement runs a block of code e if a conditio
on is true. For syntactic reassons, you musst enclose the
conditionn in round braackets. For exaample:

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())

• A for loop runs a set o


of statements while a condition is true, and this condittion is typicallly based on
the value of a control variable.
v The e
execution of a for statement is determinned by three e elements
separatedd by a semicolon: a start co
ondition, an en
nd condition aand a step. Fo
or example:

for (in
nt i=0; i<10; i++) {
Plump
pUpAPillow();
}

IIn this example, the start co


ondition sets a counter variable i to zero
o. After Plump
pUpAPillow()) is run, the
s
step statemennt i++ runs an nd adds one to
t the counterr. Then, if the end condition
n (j < 10) is sttill true, the
l
loop continue
es. In this exam
mple, the funcction PlumpUUpAPillow() rruns 10 times..

All three loop


A p types use an end conditio on to break ouut of the loop.. You can also
o add a break
k statement to
o
t
those within tthe block thatt defines the body
b of a loop
p to perform tthe same taskk. When the exxecution
3-16 Introduction to JavaScript

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

JJavaScript is aan excellent laanguage in whhich to write o


object-oriente
ed web applications. Like m
many other
m
modern langu uages, it allow
ws you to defin
ne objects thaat have prope ds, and events. This subject
erties, method
i described in
is n more detail in a later moddule.
J
JavaScript pro
ovide several b
built-in objectt types, includ
ding:

• 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.

The Date obje


T ect type, whicch enables youu to work with h dates. JavaSScript represen
nts data intern
nally as the
n
number of miilliseconds elaapsed since 01
1/01/1970 and d all date metthods use the GMT+0 (UTC C) time zone,
e
even though yyour compute er may displayy a time that is consistent w
with your timee zone.

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.

• The Array y object type,, which enable


es you to creaate and work w with a zero-based, dynamic-length
array of values.
v Arrays also provide methods enab bling you to ssearch for mattching items in an array, to
o
change thhe order of elements in thee array, or to ttreat the arrayy as a stack orr queue structture.

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:

var seasonsArray = ["Spring", "Summer", "Autumn", "Winter"];

• 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.

var re = new RegExp("\\[dh\\]og");


if (re.test("dog")) {...}

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.

• pairs are separated by a comma.


Property name-value p

• All prope
erty names and
d values mustt be double-q
quoted stringss.
• Trailing commas in objjects and arraays are forbidd
den.

• The property list is encclosed in a paiir of curly braces.

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"
}
]

JJSON has beccome increasinngly importannt as it is curre


ently the de faacto format fo
or passing datta in an AJAX
r
request betwe
een a web pag ge and a webb server. JavaScript providess APIs for converting data into JSON
f
format (JSON
N.stringify), and for parsing
g JSON data (JSON.parse)..
3-20 Introduction to JavaScript

Additional Reading: The full JSON syntax can be found at


https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON.
Programming in HTTML5 with JavaScrippt and CSS3 3-21
1

Lesson 2
Intro
oduction to the Docu
ument O
Object Model

You use HTML to define th


Y he structure off a page, but web
w browserss use another W3C standard d, the DOM,
t represent tthat structure internally. In this lesson, yo
to ou will learn the fundamentals of the DO
OM, using it
t add a level of interactivity to your pag
to ges with the h help of some JJavaScript cod
de.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Describe the purpose aand basic stru


ucture of the D
DOM.

• Select ele
ements by usin
ng the DOM.
• Add, remove and mod
dify elements by
b using the D
DOM.

• Handle evvents for conttrols on a web


b page.
3-22 Introducction to JavaScript

Th
he Docum
ment Objecct Model

Alll modern brow


wsers implement an objectt model called d the DOM de evised by the W
World Wide Web
W
Co
onsortium (W3 3C) to represeent the structu page. The DOM provides a programmatic API,
ure of a web p
enabling you to
o write JavaScrript code thatt performs com mmon actionss such as finding the title o
of the page,
changing the co g a page, addiing new elements to the paage, and much more.
ontents of a list, redirecting
The DOM define es the properrties that a scrript can chang ment in the page, and what actions can
ge for an elem
be
e made on the e document ass a whole.
Mo
ost modern browsers provide access to the
t following APIs:

• The DOM C Core, which de


efines the bassic interfaces ffor accessing a document, elements,
e attrributes, and
text on a paage.
• The DOM EEvent Model, wwhich definess the basic set of UI and pag
ge events and
d how to add and
remove han
ndlers for events in generall.

• 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.

• The DOM LLoad and Savee API, which e


enables you to
o serialize and
d deserialize DOM
D represen
ntations of
the page in
nto an XML do
ocument.

• The DOM V Validation API, which contains methods to


t dynamically update documents so the
ey become
valid againsst the HTML 4.01
4 specificattion.
The DOM speciffication was completed in 2 2004 and assu w page is wrritten in HTML 4.01 or
umes that a web
XH
HTML 1, which
h were the staandards availaable at that tim urrently under way to simp
me. Work is cu plify the
DO
OM specificatiion and to up TML5 and CSSS3. This work is currently kn
pdate it for HT nown as DOM4.

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

Aftter a page has loaded, a co


ommon action n when scripting against the DOM is to ffind an element or set of
ele
ements to que ery or manipu mple, you mayy need to obttain a referencce to a list so that you
ulate. For exam
can populate it with elements retrieved froom a web servvice. The DOMM represents tthe various paarts of a
do
ocument as a sset of arrays:

• The forms array contains details of alll the forms in the documen
nt.

• The imagess array contains all the images in the document.


• The links array contains all the hyperlinks in the do
ocument.

• The anchorrs array contaains all the <a> tags in the document wiith a name atttribute.

• The applets array contaiins all the app


plets in the do
ocument.
• The areas aarray containss all the image
e maps in the document.

Alll of these colle


ections are ch
hild propertiess of the documment object. This object reepresents the document
as a whole. You can use dot n notation to acccess each colllection, and aany property, method, or evvent
deefined by the D DOM. To acce ess individual elements in a collection, yoou can use an
n indexer or re
eference it
byy the value of its name attribute. For exam mple, if you h
have the followwing simple contact form oon a page:

<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:

var userNameBox = document.getElementById("nameBox");


var username = userNameBox.value;
3-26 Introducction to JavaScript

Ad
dding, Removing, and
a Manip
pulating O
Objects in the DOM
M

Aftter you have found


f an elem
ment or set off elements to w
work with, the
e next step is often to chan
nge them in
some way, adding new child elements, mo odifying existing elements oor removing tthem.

The DOM Core API defines se


everal method
ds to create new objects fo
or a documentt, including:

• document.ccreateElementt(tagname)

• document.ccreateTextNod
de(string)

• document.ccreateAttributte(name, value
e)

• document.ccreateDocume
entFragment

Alll four of these


e methods acttually create a DOM node o object, which is the genericc representatio
on of an
ele
ement, text, or attribute in the DOM. Aftter you have ccreated the DO OM node object, you add it i to the
DOOM. The simplest way is to call documen nt.getElemen ntbyId() to reetrieve the parrent element to which
you wish to app ply this object,, and then calll one of the fo
ollowing methods on this e element:

• appendChiild(newNode
e), which addss the new nod
de as the last child
c of the se
elected eleme
ent.

• insertBefore(newNode, existingNod de), which ad


dds the new no
ode into the D
DOM before but
b as a
sibling to th
he given existtingNode.

• 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:

• childNodess, which returrns all the child nodes of a node.


• firstChild, w
which returnss the first child
d of a node.

• 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.

The following example shows how to modify a list in a page.

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:

• removeChild(node), which removes the target node.

document.removeChild(
document.geElementById("VenueList").firstChild
);

• removeAttribute(attributeName), which removes the named attribute from the element node.

var list = document.getElementById("VenueList");


list.removeAttribute("id");

• removeAttributeNode(node), which removes the given attribute node from the element.

var list = document.getElementById("VenueList");


list.removeAttribute(list.attributes[0]);

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:

• addEventListener(even ntName, listenerFunction,, bubbles), which adds the


e listener functtion to the
element forr the given ev
ventName. Yo ou can pass th
he listenerFun me or as an anonymous
nction by nam
function.

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

• removeEventListener(event, listenerFunction, bubbles), which removes the listener function from


the element for the given eventname.

helpIcon.removeEventListener("mouseover", "ShowHelpText", false);

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.

Binding an action to an event with the DOM

Binding an action to an event with the DOM


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Binding events with JQuery</title>
<script type="text/javascript" src="Scripts/jquery-1.8.0.js"></script>
</head>
<body>
<form>
<p>
<label>Write Your Name:
<input type="text" id="NameBox" /></label></p>
<input type="button" id="submit" value="Click to submit" />
</form>
<div id="thankYouArea"></div>
<script type="text/javascript">
function sayThankYou() {
var userName = document.getElementById("NameBox").value;
var thankYou = document.createElement("p");
thankYou.textContent = "Thank you " + userName;
document.getElementById("thankYouArea").appendChild(thankYou);
}
document.getElementById("submit").addEventListener("click", sayThankYou);
</script>
</body>
</html>
3-30 Introducction to JavaScript

Lesson 3
Introd
duction
n to jQu
uery

Wrriting JavaScriipt code to co


ontrol the browser and the contents of a web page haas often been a time-
consuming taskk. The different ways that brrowsers have implemented d the DOM ovver the years have
h been
sim
milar, but almoost never the same. Writingg JavaScript code has often
n meant a lot of effort to su
upport all
bro
owsers, or commpromising yyour site to fully support onnly one or two
o browsers.

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.

• Select and traverse


t throu
ugh set of elem
ments by usin
ng jQuery.

• Add, removve, and modifyy elements fro


om a page byy using jQueryy.
• Handle con
ntrol events byy using jQueryy.
Programming in HTTML5 with JavaScrippt and CSS3 3-31
1

T jQuerry Library
The

The jQuery lib


T brary is a single JavaScript ffile that, once referenced in
n your page, aallows you to build
p
potentially co
omplex, cross-browser functtions and effe ects for your site
s with much h less effort th
han it would
t
take without it.
i
jjQuery providdes a great deal of function nality on top o
of which manyy people have
e built extensio
ons and
p
plug-ins. The jjQuery libraryy includes the
e following APPIs:

• 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.

• Selector Engine. The jQuery


j selecto
or engine ("sizzzle") is one o
of the main hig
ghlights of jQ
Query. It
enables yyou to quicklyy select a grou
up of elements by using CSS selectors.
• Filtering and Traversing. jQuery defines many ffunctions for aadding criteria
a to your elem
ment selection
n
(for exam
mple, first, con
ntains, and la
ast) and also for traversing the DOM tree
e (for example
e, next, prev,
parent, aand siblings).
• Create, MModify and DDelete. jQueryy enables you to modify the e text contentt, attributes, and
a styles on
a selected
d element, as well as to inse
ert and removve elements frrom the DOM M.

• Presentaation. jQuery enables


e you to create new, change existing, and remo
ove CSS styless, as the need
arises.

• 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.

• AJAX. jQuery providess a number off alternative methods


m for m
making AJAX requests to bo
oth third-
party web
b services and
d your own we more content.
eb server for m

• 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

<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>

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.

Adding jQuery to the page


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.8.0.min.js"></script>
</head>
<body>

<script type="text/javascript">
$(document).ready(function () {
// some code
});
</script>
</body>
</html>

In the previous code example,

• The dollar sign is shorthand for the core jQuery() function.

• $(document) selects the entire document.

• 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

IIn this demon


nstration, you will see how to
t add the jQuery library to
o a website prroject by using g the
P
Package Manager in Visuall Studio 2012,, and how to enable
e jQueryy IntelliSense ffor script filess in your
p
project.

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.

Note: Itt does not maatter whether you select the


e Visual Basicc or Visual C#
# templates in
n the
lleft pane; the templates forr both languages enable yo ou to create H
HTML5 web paages and
i
implement functionality byy using JavaSccript.

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.

12. On the File menu, click Save jQueryDemoTest.

Enable jQuery IntelliSense

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.

/// <reference path="jquery-1.8.1.js" />

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
});

8. On the File menu, click Save All.

9. Close Visual Studio 2012.


Programming in HTTML5 with JavaScrippt and CSS3 3-35
5

S
Selecting Elements and Traversing the
e DOM by
y Using jQ
Query

One of the maain features o


O of jQuery is its powerful seleection engine
e. The base sellector function
n, jQuery(),
o $(), uses th
or he same selecttor syntax as CCSS. This meaans that you caan search for a set of elements by:

• Tag name
e. For example
e, $("h2")

• Element IID. For examp


ple, $("#logo"))

• Element cclass. For exam


mple, $(".blue")

• An attribu
ute on an elem
ment. For example, $("inpu
ut[type=text]"))

• Using pse
eudo-classes. For example, $("p:first")

• Concaten ple, $("section > h2:last")


nating CSS selectors together. For examp

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.

IIn this example, the each fu unction is use


ed to iterate o
over all the h2
2 elements in a document and
a change
t
their CSS style
es so that theiir text contentt is red.

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>

jjQuery includes many functions for trave


ersing and filttering a selectted set of elem
ments. The folllowing list
h
highlights som
me of the morre commonly used function ns:

• eq(index x), which returrns the single element at th


he given indexx. Since sets h
have a zero-baased index,
eq(0) retu
urns the first e
element of a sset and eq(9) returns the te
enth element, etc.

$("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.

$("nav > li").first();

• next() and prev(), which return the element immediately following or preceding the selected
element.

$("nav").next();

• size(), which returns the number of elements in the selected set.

$("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

After you havve selected a set


A ep is usually to modify them
s of elementts, the next ste m in some wa ay, perhaps byy
a
adding some content, chan nging a style, or adding to or removing them
t from the web page. jQuery
i
includes manyy functions fo
or manipulatinng sets of elem
ments. You typ pically use the
ese methods w with the
s
selector function to determmine the elemments to chang ge. The follow
wing list highliights some off the more
c
commonly used functions:

• addClasss(className)), which adds the given CSSS class to each


h of the eleme
ents in the sett.

$("p").addClass("strike");

• append( htmlString )), which adds the given HTM


ML at the end
d of the conte
ent of each ele
ement in the
set.

$("ul")
).append("<li>The new la
ast list ite
em</li>");

• detach(),, which removves all the elements in the set


s from the D
DOM.

$("#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>");

• val(), whiich gets and ssets the curren


nt text value o
of the first element in the set.

$("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

Additional Reading: You can find a full list of manipulation functions at


http://go.microsoft.com/fwlink/?LinkID=267721.
Programming in HTTML5 with JavaScrippt and CSS3 3-39
9

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.

• The name e of the function to run wh


hen the event occurs, or an anonymous ffunction conta
aining the
script to rrun.

$("#subbmit").bind("click", fun
nction() {
// co
ode for click event hand
dler for the
e submit button
};

Y can use the unbind() ffunction to re


You emove the eve
ent handler, iff necessary.

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.

• focus(), focusin(), focusout() : Binds to element focus events.


• keydown(), keyup(), keypress() : Binds to user keyboard input events.

• hover(), mousedown(), mouseup(), mouseenter(), mouseleave(), mouseout(), mouseover(),


mousemove() : Binds to mouse and cursor-related events.

• load(), unload() : Binds to events triggered when a specified element is loaded or unloaded on the
page.

• select() : Binds to element selection events.


Each method can be passed to either the name of the handler function or to the function itself.
Programming in HTTML5 with JavaScrippt and CSS3 3-41
1

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

• Use JavaSScript code to


o programmattically update the data disp
played on an H
HTML5 page.

• Handle th
he events thatt can occur when a user intteracts with a page by using
g JavaScript.
E
Estimated Tim
me: 60 minutes

• Virtual Machine: 20480


0A-SEA-DEV11-03, MSL-TM
MG1

• User Nam
me: Student
• Password
d: Pa$$w0rd
3-42 Introduction to JavaScript

Exercise 1: Displaying Data Programmatically


Scenario
In this exercise, you will create the Schedule page that displays a list of sessions.

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.

The main tasks for this exercise are as follows:

1. Review the existing code for the Schedule page

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

5. Run the web application and view the Schedule page

X Task 1: Review the existing code for the Schedule page


1. Start the MSL-TMG1 virtual machine if it is not already running.

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:

FIGURE 3.1: THE SCH


HEDULE PAGE
E WITH SESSIONS DISPLA
AYED

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

Exercise 2: Handling Events


Scenario
In this exercise, you will add check boxes to the Schedule page to enable the user to specify which
sessions should be displayed, according to the tracks that they are in.

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.

The main tasks for this exercise are as follows:

1. Add checkbox HTML elements


2. Write code to get the checkbox elements from the Schedule page

3. Add click event listeners for each checkbox

4. Update the displaySchedule function to display the sessions for selected tracks

5. Run the web application and view the Schedule page

X Task 1: Add checkbox HTML 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.

2. In the schedule.htm file, before the schedule list, add two checkboxes with labels for track 1 and
track 2.

3. Set the checkboxes id attributes to be show-track-1 and show-track-2.


4. Mark the checkboxes as checked by default.

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 3: Add click event listeners for each checkbox


1. At the end of the schedule.js file, add an event listener for the click event of each checkbox. The
event handler for each checkbox should call the displaySchedule function.

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).

Note: Examine the track1Checkbox and track2Chebox elements to determine which


track the user has selected.
3-46 Introduction to JavaScript

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.

4. Verify that if neither track is selected, no sessions are listed.

Note: The sessions for Track 1 are:

• Registration

• Moving the Web forward with HTML5

• Diving in at the deep end with Canvas

• WebSockets and You

• Coffee and Cake Break


• Building Responsive UIs

• A Fresh Look at Layout

• Lunch
• Getting to Grips with JavaScript

• Web Design Adventures with CSS3

• Closing Thanks and Prizes

The sessions for Track 2 are:

• Registration

• Moving the Web forward with HTML5

• New Technologies in Enterprise


• Coffee and Cake Break

• Fun with Forms (no, really!)

• Real-world Applications of HTML5 APIs


• Lunch

• Transformations and Animations

• Introducing Data Access and Caching


• Closing Thanks and Prizes

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

All variabless in JavaScriptt are strongly typed, and yo


ou must speciify the type
of a variablee when you create it. True or False?

Question
n: What is the purpose of th
he DOM?

T
Test Your Kno
owledge

Question

Which jQuery function in


ndicates that the contentss for a page have been load
ded into the
browser?

Select the correct answerr.

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 

Lesson 1: Creating HTML5 Forms 4-3 

Lesson 2: Validating User Input by Using HTML5 Attributes 4-9 


Lesson 3: Validating User Input by Using JavaScript 4-16 

Lab: Creating a Form and Validating User Input 4-22 

Module Review and Takeaways 4-29 


4-2 Creating Forms to Collect and Validate User Input

Modu
ule Ove
erview

Weeb applicationns frequently need to gatheer user input in order to pe


erform their taasks. A web page needs
to be clear and concise about the input exxpected from a user in orde er to minimizee frustrating
miisunderstandinngs about the e information that the user should providde. Additionally, all input m
must be
validated to enssure that it conforms to the
e requirementts of the appliication.
In this module, yyou will learn how to defin
ne input formss by using thee new input tyypes available in HTML5.
Yoou will also see
e how to valid
date data by using
u HTML5 aattributes. Finnally, you will learn how to perform
exttended input validation byy using JavaScript code, andd how to provvide feedback to users when their
inp
put is not valid
d or does nott match the ap
pplication’s exxpectations.

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.

• Write JavaSScript code to perform valid


dation tasks th mented by using HTML5
hat cannot easily be implem
attributes.
Programming in HTML5 with JavaScrript and CSS3 4-3
3

Lesson 1
Creatting HT
TML5 F
Forms

HTML forms aare the primarry mechanism


H m used by man ny web appliccations to retrieve user inpu
ut. Previous
v
versions of HTTML provided d basic forms ffacilities and d
depended on the server pro ocessing the data
d
s
submitted This process offten resulted in poor performance and
by the user in orrder to validatte this data. T
l
low user satisffaction due to
o the number of round-trip ps required beetween the user's browser aand the
s
server. HTML5 5 provides an improved exp perience by enabling much h more functio onality to be performed in
t user's browser before the data is sub
the bmitted to the e server.

IIn this lesson, you will learn


n about the ne
ew input type
es available in HTML5 that e
enable a brow
wser to
p
provide more responsive and immediate e feedback to a user.

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.

• Describe the attributess available witth the new HT


TML5 input tyypes to improvve the user's e
experience.
4-4 Creating Forms to Collect and Validate User Input

Declaring a Form in HTML5

Usse the <form>


> element to define an inp
put form in an HTML5 page
e.

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 <form> ele


ement has the
e following atttributes:

• The name oof the form. T


This attribute is
i used by the
e server to refe
erence the fie
elds on the forrm during
processing.

• 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.

The most generric of all the in ng <input type="text" /> p


nput types is ttext. Specifyin produces a texxt box in
wh
hich the user eenters data. However,
H HTMML5 provides a range of oth her types that you can use with
w the
<input> eleme ent to better d define the kindd of data thatt is expected, providing for better client--side
validation and fformatting.

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

Noot all input typ


pes create texxtboxes: butto
on, checkbox x, radio, colorr, and range ccreate specificc controls
de
esigned to gatther the appro opriate type o
of data. The tyype file trigge
ers an interacttion with the o
operating
sysstem to enablle the user to upload a file to the server. The types submit, reset, aand image alll create
bu
utton controls.

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 <textarea> > element is similar


s to <inpput> in that it accepts type
ed input, but tthe control is rendered
as a multi-line area
a using a fixed-width fon utes cols and rows control how wide it is and how
nt. The attribu
maay rows it has. You can set its maxlengtth attribute to o set the maxiimum number of characterrs it will
acccept. You use it like this:
Programming in HTML5 with JavaScript and CSS3 4-7

<textarea id="carDescription" name="carDescription" cols="80" rows="5"


placeholder="Enter a short description of your car" maxlength="399"/>

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:

<select id="carManufacturer" name="carManufacturer">


<optgroup label="European">
<option value="volvo">Volvo</option>
<option value="audi">Audi</option>
</optgroup>
<optgroup label="American">
<option value="chrysler">Chrysler</option>
<option value="ford">Ford</option>
</optgroup>
</select>
4-8 Creating Forms to Collect and Validate User Input

HT
TML5 Inp
put Attribu
utes

HTTML5 makes extensive


e use of attributes tto improve the user experie ence and to gguide the userr through
forrm completion. Many of th
hese attributess are specific tto each of the
e input types. For example, the
nuumber input ttype supports the max, min n, step, and value
v attribute
es to indicate the maximum m,
miinimum, incre
ement, and deefault values, rrespectively. A
As with the inpput types, nott all of these attributes
a
are
e widely imple
emented at present.

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.

Alsso new to HTMML5 is the autocomplete aattribute. If thhe user has en


ntered the sam me data beforre, the
preevious value is automatically copied into he user experience. This
o the input byy the browser,, improving th
can be applied tto either an in
ndividual field
d or the form.

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 required atttribute indicaates that a field is mandato


ory and that th
he form shoulld not be subm
mitted if it
is left
l blank.

The pattern atttribute enable


es you to apply a regular exxpression to a text input fie
eld to ensure tthat it
conforms to a specific pattern
n.

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

When you havve completed


W d this lesson yo
ou will have gained
g an und
derstanding of validation, w
why it is
n
necessary, and
d how to implement validaation by using HTML5 formm 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.

Vaalidation occurs in two places:


• On the cliennt. When the user completes the form, some
s data can
n be validated
d by HTML maarkup and
JavaScript ccode running in the browse
er.

• On the servver. When the form is subm


mitted, the bacck-end processs must verify that the dataa is correct
before proccessing it.

Altthough perforrming validation twice mayy at first seem m inefficient, va


alidating data
a in the client and on the
serrver achieves different goals. Client-side validation is important beccause it signifficantly improoves the
useer’s experiencce. It can take several secon
nds to post a form
f to a webb server and g
get the reply. TThis wait
can be avoided if the form caan detect simp ple errors befoore it is subm
mitted. As a bo
onus, it also re
educes the
loaad on server rresources if an
ny obvious errrors can be picked up beforre the form is submitted.
Altthough some data checks m may be repeated on the server, this is no
ot considered duplication. The
T URL
thaat receives the
e data may be
e referenced b her than the fform, and the server can make no
by sources oth
asssumptions about the data it
i receives.

dation on the server can


Form validation is limited in iits scope, and aims to pick up very simple errors. Valid
be
e far more fine e-grained than on the cliennt browser beccause a serverr has far moree resources at its disposal
and has a broad der context foor processing the
t data. For e nt-side validattion can ensure that a
example, clien
password entere ed by a user cconforms to a particular pattern or compplexity, but on
nly server-side
e validation
can verify that tthe password is correct.
Programming in HTTML5 with JavaScrippt and CSS3 4-11
1

E
Ensuring t
that Fields are Not Empty

To ensure thaat the user entters data in a mandatory fie


T eld, add the H
HTML5 attribu ute required tto the
<input> elem ment. If the usser attempts to submit the form before pproviding a vaalue, it will no
ot be posted
t the server. The following
to g example sho ows how to usse the require
ed attribute:

<input id="contactNo" name="co


ontactNo" ty
ype="tel" placeholder="E
Enter your mobile
m
number"
" required="required" />
>

The required attribute worrks with the in


T nput types tex xt, search, url, tel, email, p
password, nu umber,
c
checkbox, radio, and file, and with the input types that pick datess where they area implemen nted. How the
e
b
browser informs the user thhat a mandato ory field is em
mpty is a functtion of the bro
owser; Interne
et Explorer
h
highlights misssing fields with a red border and a messsage.
4-12 Creatingg Forms to Collect aand Validate User Innput

Vaalidating Numeric IInput

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"
" />

The user can typ


pe anything in nto the textbo
ox, but unless it is a numbe
er between 0 aand 100, the fform will
no
ot pass validation, and will n
not be submittted.

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.

<input id="orderRef" name="ord


derReference
e" type="text" pattern="
"[0-9]{2}[A-
-Z]{3}"
title="
"2 digits and 3 uppercas
se letters" />

T pattern aattribute can be


The b used with tthe input type
es text, searcch, url, tel, em
mail, and passsword.

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

Sttyling Fields to Prov


vide Feedback

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;
}

This is helpful, but


b static. The ese colors will not change aas the form is used. Better still
s would be to use
color to indicatee that validation has been successful.
s Remember that although Inte ernet Explorer styles
fields that have failed validation, this same
e styling is nott universal and
d other browssers may behaave
diffferently

o dynamically use validation


To n to change th he color of the border, creaating instant ffeedback of suuccessful
validation which
hever browserr the user is ru
unning, you caan amend the e stylesheet ass shown in the
e following
code example. TThis technique
e works by de etecting the vaalidation state
e of the input control by ussing the
valid and invaliid pseudo-cla
asses, and prooviding a rule for the borde er color for eacch state.
Programming in HTML5 with JavaScript and CSS3 4-15

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:

• Describe hoow to use the onSubmit evvent of a form


m to perform vvalidation and
d override the
e default
validation messages
m implemented by the browser.

• Perform complex data vaalidation by using regular e


expressions.

• 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

You can use e


Y event handlerss to validate fforms input da
ata with JavaSScript. When tthe user subm mits a form,
t submit evvent is raised, and you can arrange to caatch this eventt to validate aand cross-check the data in
the n
e
every field as a unit prior to
o the form beeing sent to th
he server for p
processing. If the
t validation n is successful,
t event han
the ndler can return true and th he form will be submitted. If the validatioon fails, the evvent handler
s
should return false, which pprevents the pprocess from ccontinuing.

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>
>

The JavaScriptt function vallidateForm re


T eferenced by the code in th he onsubmit attribute should examine
e
each field in o
order and validate it. If any field fails valiidation, the fu
unction return ns false, otherw
wise it returnss
t
true. This appproach enables you to perfo orm more com mprehensive cchecking of eaach input field d, and you
c also crosss-check and va
can alidate fields aagainst each other
o and to other
o data sources (for example, if the
f
form enables a user to purcchase goods, some produccts may not be e available if tthe user is und
der 18 years
o
old).

Each input fie


E eld in a form also
a raises an input
i event, aand you can ccatch this evennt if you only need to
p
perform validation on a character by cha aracter basis ffor selected fields rather than for an entiire form. This
v
validation occcurs as the use
er enters the ddata rather thhan when the form is submitted, but if th he data is not
v
valid you can set the Custo omValidity fla ag to indicatee that the formm should not be submitted until the
d
data is correctted. For exam
mple, if the form contains an n input field with
w an id of cconfirm-age, you can
v
validate the d
data entered inn the field like
e this:

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

ageInput.setCustomValidity("Age is invalid. Please specify a value between 18 and


120");
} else {
ageInput.setCustomValidity("");
}
}
...
var ageInput = document.getElementById("confirm-age");
ageInput.addEventListener("input", checkAge, false);

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

de to emulate HTML5 inputt types and attributes that the


You can use JavaScript cod
Y t user's browser does
n support, o
not or to perform validation thaat is beyond tthe capabilitie ML5 input attributes. For
es of the HTM
e
example, the following form
m defines an input field named scoreFie eld:

<form id="scoreForm" method="p


post" action
n="..." onsubmit="retur
rn validateF
Form();" >
...
<div id="scoreField" class="
"field" >
<in
nput id="score" name="sc
core" type="
"number" />
<la
abel for="score">Score:<
</label>
</div
v>
...
</form>
>

You can use the following JJavaScript cod


Y de to check if a value enterred by the use
er in the score
eField field is
a valid integer:

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>

The following JaavaScript code


e performs the validation:

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.

The following CSS displays a different bo


T order color arround an inpu
ut field depend
ding on whetther it is
t
tagged with the validatedFine of validaationError claass:

.valida
atedFine {
borde
er-color: #0f0;
}
.valida
ationError {
border-
-color: #f00;
}

The JavaScriptt code shown


T n below validaates the penallties field and
d sets the className prope
erty to
v
validationErrror or to valid
datedFine acccording to thee outcome:

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:

• Create a forrm by using H


HTML5 input e
elements and validate form
m data by usin
ng HTML5 attrributes.

• Implement extended datta validation b


by using JavaSScript.
Esttimated Time:: 60 minutes

• Virtual Macchines: 20480A 1-04, MSL-TMG1


A-SEA-DEV11

• User Name: Student


• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 4-23

Exercise 1: Creating a Form and Validating User Input by Using HTML5


Attributes
Scenario
In this exercise, you will create an HTML form that collects conference attendee registration information.

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.

The main tasks for this exercise are as follows:

1. Modify the Register Page


2. Add Form Inputs to the Register Page

3. Make the Form More User Friendly

4. Check for Missing Mandatory Data


5. Add Password Complexity Validation

X Task 1: Modify the Register Page


1. Start the MSL-TMG1 virtual machine if it is not already running.

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.

X Task 2: Add Form Inputs to the Register Page


1. Add the input elements specified by the TODO comment to the registration form:

• Do not include any validation yet.


• Use the most appropriate HTML5 input types.

• 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.

5. e that you can


Also, notice n leave fields b
blank, or enter mismatching g passwords. When you click
he data is validated by the registration server, but it w
Register, th would be more e efficient to ttrap these
o the server.
issues beforre the data is transmitted to

6. Close Intern
net Explorer.

X Task 3: Make the Forrm More Usser Friendly


1. In the regisster.htm file, modify the FiirstName input so that it aautomatically gets the focuss when the
browser loaads the registeer page.

2. Modify the Website inpu


ut to display tthe placeholder text http:/// when the page is displayyed.
3. Run the app
plication, view
w the registerr.htm page, vverify that the First name b
box has focus and that
the Websitte box containns the placehoolder text.

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

Note: T The password validation performed by th he registration


n server requires that passw
word
ccontain letterss and numberrs only. Punctuation and otther characterrs are not allo
owed.

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.

The Regisster page shou


uld highlight each missing data item, likke this:

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,}

• If the Passsword input doesn’t match the regular expression, d


display the folllowing message:

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.

Exercise 2: Validating User Input by Using JavaScript


Scenario
The conference registration form requires that the Password and Confirm Password inputs match. You
cannot implement this type of validation by using HTML5 attributes. In this exercise, you will extend the
registration form validation by using JavaScript. In addition, you will write code to style any input that is
not to attract the user’s attention.

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.

The main tasks for this exercise are as follows:


1. Write Code to Get the Contents of the Password Input Elements

2. Write Code to Compare the Password and Confirm-Password Inputs

3. Write Code to Display a Custom Error Message if the Passwords Differ

4. Add Input Event Listeners to the Inputs to Call the checkPasswords Method

5. Style Invalid Elements that are Not Valid

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 2: Write Code to Compare the Password and Confirm-Password Inputs


1. The register.js file contains a function called checkPasswords that should examine whether the
password and confirm-password inputs contain the same text. This function is currently empty (apart
from some comments). In the checkPasswords function, add code to test whether the two password
inputs have the same value and store the Boolean result in a variable named passwordsMatch.
Programming in HTML5 with JavaScript and CSS3 4-27

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.

X Task 5: Style Invalid Elements that are Not Valid


1. In the ContosoConf project, open the styles\pages\register.css file.

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??

Question n: If you perfo


orm validation
n in the browsser, is it necesssary to perforrm the same
validation
n checks in the server code that processees the data, or is this additional processing
redundan nt?

V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.

Statement Answer

You should always use th he input even


nt to validate data
d that a usser enters
into a field, in preference
e to the subm
mit event of th
he form. True or False?
 
5-1

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 

Module Review and Takeaways 5-26 


5-2 Communicating with a Remoote Server

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

A web browseer interacts wiith a web app


plication by sending and recceiving HTTP requests. Sim milarly, a web
p
page can makke requests too access additiional remote resources, and d this is typicaally performed
d by using
H
HTTP requests. The HTTP nnetwork proto ocol is relatively simple, butt HTML5 incorrporates the
X
XMLHttpReq quest object that
t provides a programma atic interface tthat a JavaScrript application can use to
s
send eive HTTP requests.
and rece

IIn this lesson, you will learn


n how HTTP w web methods are used by th he web browsser to access e
external
r
resources from
m a web page e. Then you wwill learn how tto use the XM
MLHttpReque est object to load data
f
from a remote e website. Finally, you will learn
l how to uuse the XMLHHttpRequest object to sen nd requests to
o
a web service and to proce ess any responnse that is rece
eived.

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.

• Describe how to handlle errors that can occur when sending re


equests and re
eceiving respo
onses.

• Handle th
he data return
ned by a serve
er in response
e to a request..

• Process th
he received data asynchron
nously.

• Send messsages that traansmit data to


o a server.
5-4 Communicating with a Remoote Server

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();

You can then use this objecct to initiate a remote requ


Y uest. To do thiis, you set prooperties that specify the
U of the rem
URL mote data, annd that specifyy the type of d
data in the reqquest; this is tto enable the server
r
receiving the request to co
orrectly parse tthe data that it receives. Th
he following code
c shows ann example:

var url = "http://contoso.com/


/resources/...";
request
t.open( "GET
T", url );
request
t.setRequestHeader("User
r-Agent", "X
XMLHttpRequest");

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:

request.open(method, url, false);


Programming in HTML5 with JavaScrript and CSS3 5-7
7

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.

Note: TThe try…catch nism that enables


h construct in JavaScript is a general-purrpose mechan
yyour code to catch and han ndle unexpectted exception ns that occur w
when your JavvaScript code
r
runs. You can wrap a blockk of JavaScriptt code in a tryy statement an
nd catch any errors that miight
o
occur while th
his block of co
ode is running
g, like this:
5-8 Communicating with a Remote Server

try {

/* JavaScript code that might trigger an exception */


...

} 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

You can retrie


Y eve the data returned by thhe server in re
esponse to the
e request by e
examining the
e
r
responseTex t property of the request o
object.

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

IIf you are perfforming an assynchronous qquery (the deffault case), yo


ou should waitt for the respo
onse to be
a
available befo
ore attempting g to read the responseTex xt property. The XMLHttpR Request obje ect provides
t readystattechange eve
the ent that you can use to deteect whether data
d has been returned. Thiis event
o
occurs wheneever the state of the XMLHttpRequest o object change es. The XMLHttpRequest o object has a
r
readyState property that ccan have one of the followiing values:

0 The XMLHtttpRequest object


0: o is has n
not been open
ned.

1 The XMLHtttpRequest object


1: o has bee
en opened.

2 The XMLHtttpRequest object


2: o has sen
nt a request.

3 The XMLHtttpRequest object


3: o has starrted to receive
e a response.

4 The XMLHtttpRequest object


4: o has finished receiving
g a response.

To receive datta asynchrono


T ously, you can
n create a han
ndler for the re
eadystatecha
anged event, examine the
r
readyState property, and if
i a response has
h been rece eived, read thee responseTe
ext property o
of the
r
request. The ffollowing code shows an exxample that uses the onrea nge callback to catch the
adystatechan
r
readystatechhange event.

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

HTTTP GET reque ests return daata to the brow


wser from a seerver. You cann also use HTTTP POST requ uests to
sennd data from the browser tto a server. Too transmit a re
equest that includes data, ccall the send()) function
as before but sp
pecify the POS ST method raather than GET T. The data to he server must be
o be sent to th
proovided as the optional bod dy parameter to the send()) function. The e body can be e any text string that the
serrver web methhod can parse e.

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

The jQuery ajax() function provides a hiigh-level wrap


T pper around tthe XMLHttpRequest obje ect that
e
enables you too send requessts and receivve responses inn a more conccise and intuittive manner. In
I this lesson,
y will learn how to use th
you he jQuery librrary to send re
equests and h
handle the responses, and aabout the
p
possible errorrs that can occcur.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Simplify yyour JavaScrip


pt code by using the jQueryy library.

• 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;
});

Note: The e jQuery librarry also include


es the post() function, whicch operates inn a similar
maanner to the g
get() functionn. The main diifference is thaat it sends the
e request by u
using the HTT
TP
PO
OST method.

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

alert("error occurred during get operation");


});

To send a GET request that returns JSON data, use the $.getJSON() method:

$.getJSON(url, body, callback);

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.

$('#container').load(url, body, callback);

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

For really fine-g


grained contro
ol of AJAX inte
eractions with
h the web servver, jQuery haas a function ccalled
$.a
ajax() that offfers a compre
ehensive set of properties and events dessigned to give e you full control over
the
e request and d its outcome. The parametter to the funcction is an objject that conta
ains a set of p
properties.
Each of these prroperties enab
bles you to sp
pecify the vario
ous elements that constitute a request, ttogether
witth functions that run when the request ssucceeds or faails with an error. The follow
wing code sho ows an
exaample:

$.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.

h the ID answer to the text response from


In the example above, the haandler sets an element with m the web
serrvice method at the URL /luckydip/ente er.

Additiona al Reading: TThe $.ajax() fuunction provid


des a comprehensive set off properties. For
F
a ccomplete desccription please refer to http
p://go.microso
oft.com/fwlinkk/?LinkID=267723.
Programming in HTTML5 with JavaScrippt and CSS3 5-17
7

S
Serializing
g Forms Data
D by Ussing jQuerry

To send formss data to the sserver by usin


T ng the $.ajax(() function, usse the POST m
method and add a JSON-
f
formatted datta property coontaining the e data to be se
ent to the parameter list.

$.ajax(
({
url: '/luckydip/enterW
WithName',
type: 'POST',
timeout: 12000,
dataType: 'text',
data: {
firstName: myForm.fname.valuee,
lastName: myForm.l
lname.value
}).done
e(...
).fail(
(...
);

Coding each field


C f on a form
m in this way gives you pre
ecise control o
over which fields are sent and what the
p
properties of the object are
e called.

You can also use


Y u the jQuerry serialize() aand serializeA ods, which will take the fiellds on a form
Array() metho
a serialize tthe entire form
and m in one state ement. When using these mmethods, you do not get to o rename the
f
fields, so theyy will be name
ed just as theyy are on the fo
orm.

The output fro


T om the metho ods is differen
nt. The serializze() function generates a list of fields an
nd values
f
formatted g. The serializzeArray() funcction generates a JSON-forrmatted arrayy of field
as a query string
n
names and vaalues. You can
n use the seriaalizeArray() ffunction like this:

$.ajax(
({
url: '/luckydip/enterW
WithName',
type: 'POST',
timeout: 12000,
dataType: 'text',
data: {
('#myForm').serial
lizeArray();
}
}).done
e(...
).fail(
(...
);

A data properrty set in this w


way producess a JSON arrayy similar to th
his:
5-18 Communicating with a Remote Server

[
{ 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.

Additional Reading: For further discussion and a reference visit


http://go.microsoft.com/fwlink/?LinkID=267724 and
http://go.microsoft.com/fwlink/?LinkID=267725.
Programming in HTTML5 with JavaScrippt and CSS3 5-19
9

Lab: Communicating with


h a Rem
mote Da
ata Sou
urce

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..

A session mayy be very popular, so the w


web service willl return the n
number of atte
endees who h
have selected
i You will need to handle this response and display a message to the attendee when they haave selected a
it.
p
potentially bu
usy session.

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

• Virtual Machines: 2048 11-05, MSL-TMG1


80A-SEA-DEV1

• User Nam
me: Student
• Password
d: Pa$$w0rd
5-20 Communicating with a Remote Server

Exercise 1: Retrieving Data


Scenario
In this exercise, you will retrieve and display the list of sessions from a web service.

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.

The main tasks for this exercise are as follows:

1. Review the Schedule Page


2. Create the downloadSchedule Function

3. Add Error Handling to the downloadSchedule Function

4. Test the Schedule Page

X Task 1: Review the Schedule Page


1. Start the MSL-TMG1 virtual machine if it is not already running.

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.

4. In the ContosoConf project, open the scripts\pages\schedule.js file.


5. Review the updated JavaScript. Notice that the previously hard-coded array of session data
(schedule) has been replaced with an empty array.

6. Also notice that the createSessionElement function has been modified to generate a star icon next
to the session title.

X Task 2: Create the downloadSchedule Function


1. In the schedule.js file, find the comment that starts with the following text:

// TODO: Create a function called downloadSchedule

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

6. In the callback, perform the following operations:

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.

X Task 3: Add Error Handling to the downloadSchedule Function


1. In the onreadystatechange callback function, after receiving the response, add code to test the
request status code. For non-200 status codes, the response object contains a message property.
Display this message by using the built-in JavaScript alert function.

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.

X Task 4: Test the Schedule Page


1. Run the application and view the schedule.htm page to verify that the list of sessions is displayed.

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

Exercise 2: Serializing and Transmitting Data


Scenario
In this exercise, you will record the sessions that an attendee selects by transmitting this data to a web
service. In addition, you will check for potentially busy sessions and inform the attendee accordingly.

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

2. Handle the Web Service Response


3. Test the Schedule Page

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.

2. In the schedule.js file, find the function named saveStar.


3. Within the function, add code to construct an XMLHttpRequest object and make a POST request to
the following URL:

"/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.

X Task 2: Handle the Web Service Response


1. In the saveStar function, if the attendee has selected the session (isStarred is true), create a callback
for the onreadystatechange property of the request object that performs the following operations:
o If the request status is 200, then parse the response into a JSON object. This object should have a
starCount property (the web service that sends the response back formats the data in this way).

o If starCount is greater than 50, display the following message by using the alert function:

This session is very popular! Be sure to arrive early to get a seat.

X Task 3: Test the Schedule Page


1. Run the application and view the schedule.htm page.
Programming in HTML5 with JavaScript and CSS3 5-23

2. Click the star next to the New Technologies in Enterprise session.

3. Verify that an alert is displayed (this session is popular).


4. Click the star next to Diving in at the deep end with Canvas.

5. Verify that no alert is displayed (this session is less popular).

6. Close Internet Explorer.

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

Exercise 3: Refactoring the Code by Using the jQuery ajax Method


Scenario
The existing code using an XMLHttpRequest object works, but it is somewhat verbose. The
XMLHttpRequest object also requires you to carefully set HTTP headers and encode content
appropriately, otherwise request data may not be transmitted correctly. In this exercise, you will refactor
the JavaScript code for the Schedule page to make it simpler and more maintainable, by using the jQuery
ajax method.
First, you will refactor the downloadSchedule function by replacing the use of an XMLHttpRequest
object with a call to the jQuery ajax method. Then you will refactor the saveStar function in a similar
manner. Using the ajax method will simplify the code by automatically encoding the request content and
setting HTTP headers. Finally, you will run the application and view the Schedule page to verify that it still
displays sessions and responds to star clicks as before.

The main tasks for this exercise are as follows:

1. Refactor the downloadSchedule Function

2. Refactor the saveStar Function

3. Test the Schedule Page

X Task 1: Refactor the downloadSchedule Function


1. Open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 3 folder.

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.

X Task 2: Refactor the saveStar Function


1. In the schedule.js file, refactor the saveStar function to use the jQuery ajax method.

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.

X Task 3: Test the Schedule Page


1. Run the application and view the schedule.htm page.

2. Verify that the list of sessions appears correctly.

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.

5. In schedule.js, change the URL in the downloadSchedule function to be /schedule/list?fail.


6. In Internet Explorer, refresh the schedule.htm page and verify that an error message is displayed.

7. Close Internet Explorer.

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.

Test Your Know


wledge

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 status propertyy should be se


et to 200 (HTT
TP OK).

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 

Lesson 1: Styling Text by Using CSS3 6-3 

Lesson 2: Styling Block Elements 6-9 


Lesson 3: Pseudo-Classes and Pseudo-Elements 6-20 

Lesson 4: Enhancing Graphical Effects by Using CSS3 6-27 

Lab: Styling Text and Block Elements by Using CSS3 6-34 


Module Review and Takeaways 6-44 
6-2 Styling HTTML5 by Using CSS3

Modu
ule Ove
erview

Styyling the conttent displayed


d by a web page is an impo
ortant aspect oof making an application attractive
and easy to use. CSS is the prrincipal mecha
anism that we
eb applicationns use to implement styling
g, and the
feaatures added to CSS3 support many of the new capab bilities found in modern broowsers.

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.

In this module, yyou will exam


mine the propeerties and valu
ues defined in hese modules, the new
n several of th
sellectors defined in CSS3, and
d the use of p
pseudo-classes and pseudo o-elements to refine those sselections.

Ob
bjectives
e, you will be able to:
Aftter completing this module

• Use the new CSS3 to style text elementss.


w features of C
• Use the new
w features of C
CSS3 to style block elemen
nts.

• 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

You have alre


Y eady seen a nu umber of coree CSS propertiies that style aand transformm text. In this lesson,
l you
w look in mo
will ore detail at tthe value rang
ges for some o of these propeerties, and you will also be introduced
t a number o
to of new CSS3 p properties thaat target text.

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.

• Demonstrate the new CSS3 properties applicable


e to text and to blocks of te
ext.
6-4 Styling HTTML5 by Using CSS3

Fo
onts and Measurem
M ments

CSSS3 adds the @font-face


@ ru
ule to supportt downloading
g fonts onto a user's compputer so that the browser
can use them too render text. CSS3 also includes a numb
ber of new ways to specify the
t size of a foont and the
spaacing around it. These meaasurements also apply to bo
oxes, columnss, images, and
d positioning.

@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.

Ussing the @fon


nt-face Rule
@
@font-face {
font-famiily: 'Roboto
oRegular';
src: url('Roboto-Reggular-webfon
nt.ttf') form
mat('truetyp
pe');
font-streetch: normal
l; // Defa
ault
font-weigght: normal;
; // Defau
ult
font-stylle: normal; // De
efault
unicode: U+0-10FFFF;; // Default
t
}
p {
font-familyy : RobotoRe
egular, "Seg
goe UI", Aria
al;
font-size: 14px;
}

The @font-face
e rule implem
ments a combination of properties that define how a browser
b should use a
fon
nt:

• y sets the nam


font-family me to be used
d for this font in other style sheet rules.
• src defines the URL to do
ownload the ffont file from and the type of font file be
eing downloaded.

• font-stretcch identifies how condense


ed or expande
ed the font is.
Programming in HTML5 with JavaScript and CSS3 6-5

• font-style identifies whether the font is italicized, oblique, or normal.

• 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.

There are six units of absolute measurement:

• Centimeters.
• Millimeters (mm): 10 millimeters = 1 centimeter.

• Inches (in): 1 inch = 2.54 centimeters.

• Picas (pc): 1 pica = 12 points = 1/6th of an inch.


• Points (pt): 1 point = 1/72nd of an inch.
6-6 Styling HTML5 by Using CSS3

• Pixels (px): 1 pixel = 1/96th of an inch.

There are seven units of relative measurement. Four are 'font-relative':


• em: 1em = the current font size of the current element.

• ex: 1ex = the height of the font's lowercase x-height, or 0.5 em if not calculable.

• ch: 1ch = the width of the font's 0 (zero) character.

• 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:

• vw: 1vw = 1% of the width of the viewport.

• vh: 1vh = 1% of the height of the viewport.

• vmin: vmin = the smaller of vh and vw.

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

The core CSS typographic p


T properties ena
able you to sttyle text by se
etting the lette
er-spacing, liine-height,
t
text-align, te
ext-decoratioon, and text-ttransform pro operties. How wever, the CSSS3 Text modulle defines
s
several more properties thaat provide eve
en greater conntrol over thee layout of youur text conten
nt. These
p
properties incclude:

• The text--indent prope


erty, which ind
dicates how faar the first line
e of each new
w text block sh
hould be
indented..

text-in
ndent: 3rem;

• The hyph hens propertyy, which indicaates how the b


browser should hyphenate words when line-
wrappingg. Possible valu hy; sequence in your text to
ues are none (no hyphenatting), manuall (use the &sh o
indicate w
where hyphen ns can be placced), and auto
o.

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;

• The text--shadow propperty, which enables


e you to
o apply shado
owing to the selected
s text. A shadow is
defined b
by four properrties:

o x-offset: How far to


t the right th
he shadow starts. Use a neg
gative value to
o move it to th
he left.

o y-offfset: How far b


below the shadow starts. Usse a negative value to movve it up.
6-8 Styling HTML5 by Using CSS3

o blur (optional): How wide the blur of the shadow is. The default is 0.

o color: Can be any color value. The default is black.

text-shadow: 0 1px 0 #000; // not supported in Internet Explorer 9 and earlier


versions.

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

The CSS box m


T model definess how browsers handle eve ery block of co
ontent on a paage, and it is the
t basis of
e
every CSS layo
out. In this lessson, you will learn about the additions iin CSS3 to the
e core box mo odel, and you
w see a new
will w way to navig gate between blocks on scrreen. You will also look in m more depth att the differentt
w
ways to lay ou
ut blocks on a page, including the new C CSS3 Flexbox x method.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to

• 3 properties applicable to the box model.


Describe the new CSS3

• Describe how to use th


hese propertie
es to lay out the items on a web page.
6-10 Styling HTML5 by Using CSSS3

New Block Propertie


es in CSS3

The basic box model


m has not been change ed in CSS3, bu
ut it does add several prope
erties that mo
odify the
waay in which bo
oxes and theirr contents are presented an
nd accessed.

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-wid dth sets the width


w of the o
outline. Possible values are tthin, medium (the default),, and thick,
or a specificc measuremen nt such as 2pxx or 1.5 rem.
• outline-sty
yle sets the lin
ne style of the
e outline. The most commo
on values used
d are none, do
otted,
dashed, and
d solid.

• outline-collor sets the co


olor of the ou
utline. Set it to
o any allowablle color value,, or invert (the
e default).
Programming in HTML5 with JavaScript and CSS3 6-11

• 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.

border-radius: 2em; // circular corners with radius 2em


border-radius: 5px/10px; // elliptical corners with radii of 5px high and 10px wide

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 hidden: Only the content within the box is shown.

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.

Multiple Column Layout


The CSS3 Multi-Column module extends the CSS box model by adding properties to set the number of
columns a box's content will be displayed in, as well as their width, padding (gap), and border (rule).

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.

Creating a Basic Cross-Browser Layout


section {
text-align: justify;
6-12 Styling HTML5 by Using CSS3

column-count : 3;
column-gap : 5rem;
column-rule : 1px solid black;
}

There are four main properties for creating multiple column layouts:

• column-count sets the number of columns to be used.

• column-width sets the width of the columns.

• column-gap sets the padding between the column.

• column-rule sets the properties of the line drawn between columns.

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

CSS enables yyou to define tthe layouts an


C nd the types o
of boxes that yyou can display on a web p
page. The CSSS
d
display propeerty determines the type off layout mode el used on a p
page. This property can havve the
f
following valu
ues:
• block: Blo
ock boxes are
e formatted do e one after another and respect padding
own the page g, border,
and marg gin values.

display
y:block;

• inline: Inline layout blo


ocks are formatted one afteer another baased on the baaseline of theiir text
content until
u they breaak down ontoo another line,, and so on. In gnore height and width
nline blocks ig
values.

display
y:inline;

• inline-bloock: Inline-bloock layout blo


ocks are formatted one afte
er another baased on the baaseline of
their textt content, butt they keep their height and width valuees.

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;

• flexbox: Flexbox layou


ut is new in CSSS3 and desig
gned to be farr more fluid th
han the otherss. You choose
e
in which d
direction boxe
es are laid out and how booxes are sized, depending o on how any exxcess
whitespacce around blo
ocks should be e handled.

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

IIn this demonnstration, you will see how the


t different CCSS layout mo
odes and posiitioning value
es affect four
s
simple boxes. You will use tthe F12 Developer Tools to
o make the ch
hanges betwee
en modes.

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>

5. On the File menu, click View in Brower (Internet Explorer).

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

The web page looks likke this:

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 Click the CSS tab to display the fullyy expanded ve


10. ersion of the layout
l rules applied to the HTML
content.

1 Right-clicck the div entry, and then cclick Add attrribute.


11.

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.

The web page now loo


oks like this:
6-18 Styling HTML5 by Using CSSS3

FIGURE 6.2: THE DIV


V ELEMENTS IIN INLINE LA
AYOUT MODE
E
14
4. Resize the b
browser windo
ow so you can
n see how blo
ocks are wrapp
ped onto the next line in in
nline layout
mode.

15. In the F12 D


Developer Too ols window, o
on the CSS tab
b, click the dissplay: inline rule,
r change it to read
display:inliine-block, an
nd then press ENTER.

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:

FIGURE 6.3: THE DIV


V ELEMENTS IIN INLINE-BL
LOCK LAYOU
UT MODE
17. In Internet Explorer, resizze the browse
er window so you
y can see h
how blocks are
e wrapped on
nto the next
line in inline
e layout mode e.

18. In the F12 D


Developer Toools window, o
on the CSS tab
b, click the dissplay: inline-block rule. Ch
hange this
rule to disp
play:-ms-flex
xbox, and thenn press ENTER

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.

Switch between positioning modes in a web page

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.

3. Type #three and then press Tab.

4. Type position: relative and then press ENTER.


5. Right-click the #three entry, and then click Add attribute.

6. Type top: 2em, and then press ENTER.

7. Right-click the #three entry, and then click Add attribute.


8. Type left: 2em, and then press ENTER.

• 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.

Close Internet Explorer, and then close Visual Studio 2012.


6-20 Styling HTML5 by Using CSSS3

Lesson 3
Pseud
do-Classses and
d Pseud
do-Elem
ments

Yoou use CSS selectors to speccify sets of ele


ements to be sstyled based on
o element, cclass, id, and attribute.
Yoou can refine tthe set of elem
ments to style in a CSS rule by concatenaating them. In
n this lesson, yyou will
leaarn how you ccan extend selectors to include runtime aand navigatio on informationn by using pse eudo-
cla
asses and pseu udo-elementss in selectors.

Le
esson Obje
ectives
Aftter completing this lesson, you will be ab
ble to:

• o-elements to add styles to text elements.


Use pseudo

• Style hyperlinks and form


m elements baased on their current state.

• Identify elements to style


e based on their position in
n a documentt.
Programming in HTTML5 with JavaScrippt and CSS3 6-21
1

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{ }

You might use


Y e the first-lettter and first--line pseudo--elements for styling text illluminations su
uch as a
d
drop-cap or a larger font foor the start off a paragraph.. The selectio
on pseudo-ele ement is usefuul for
c
changing howw content is highlighted on n screen. The b
before and affter pseudo-e elements have e several
c
common usess. The most freequent is to aadd or remove e content arou und an eleme ent. For examp ple, reset style
e
s
sheets often n
normalize how w browsers de eal with q and
d blockquote elements by removing anyy smart
q
quotes they mmight add aro ound them.
6-22 Styling HTML5 by Using CSS3

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:visited selects all visiited links.


• a:focus selects all linkss in focus.

• a:hover sselects all linkss with the currsor hovering over them.

• a:active sselects all sele


ected links.
C rules thatt match against more than one of these pseudo-classe
IIf you define CSS es, it is importtant that you
s
specify these pseudo-classe es in the following order: liink, visited, foocus, hover, and active. Iff you
r
reference themm in a different order, somme may cancel others out. A Also, a simple selector can o only contain
m
more than on ne pseudo-class if the pseud do-classes are
en’t mutually e exclusive. For example, the e selectors
a
a:link:hover a a:visited:hover are vaalid, but a:link
and k:visited isn’t because :link k and :visited are mutuallyy
e
exclusive. A lin
nk element is either an unvvisited link or a visited link.

Note: TThere are seve


eral mnemoniccs for rememb bering the correct order (LV
VFHA) for linkk
pseudo-classe
p es. One is Las Vegas fightss Hell's Ange
els. Another is Let Victoria Free Her Arm mies.

T
There are thre
ee pseudo-claasses that you frequently usse for forms e
elements:
• input:ena
abled selects all enabled in
nput controls.

• abled selects all user interfface elementss that are disabled.


input:disa

• 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:

• :first-child selects the item that's th


he first child o
of its parent. A
As an example
e, to find the ffirst element
in a list, u
use li:first-chiild.

• :last-child selects the list item that'ss the last child


d of its parentt.

• :only-chiild selects a lisst item if it is the only child


d of its parent.
• :nth-child
d(n) selects a list item if it is the nth child of its paren
nt.

• :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.

• :nth-last-of-type(n) sselects a list ite


em if it is the nth list item cchild of its parent, counting
g backwards
from its la
ast child.

Note that the numerical argument for nth-child, nth-last-child, nth


N h-of-type, and
d nth-last-of-ttype can be
s as a simplle integer, the values odd and even, or a simple form
set mula of the form xn + y whhere x and y
a integers.
are

A set of structtural pseudo-classes is also available. The


ese classes en
nable you to select elementts based on
t current structure of the
the e document. These
T classes include:
i

• E:root selects a docum


ment's root ele
ement. For an HTML docum
ment, it will alw
ways select th
he <html>
element.
• E:empty selects an ele
ement of type E if it has no children or te
ext content.
6-26 Styling HTML5 by Using CSS3

• E:target selects an element of type E if it is the target of a referring URL.

• 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

The web is a ffar more colorrful place now


T w that most mmodern browse ers have adop pted CSS3. Preeviously,
d
developers wo
ould need to use additiona al graphics to add backgrouund gradientss or resort to vvarious items
o trickery to rotate and traansform graph
of hics elements. Many of the
ese tricks were
e browser dep pendent,
r
resulting in a poor experiennce for users running
r brow
wsers for which
h the featuress were not dessigned.

The new color and backgro


T ound values, aand the graphhics capabilitie
es provided byy CSS3, now eenable
d
developers to
o perform thesse tasks in a sttandardized way
w that will work
w in any co
ompliant browwser. In this
l
lesson, you wiill look at the new color values you can give
g to prope
erties, and howw you can inco
orporate
m
multi-image backgrounds into a web pa
b age. You will aalso see how tto perform simmple transform
mations on
a element an
an nd how to cre eate simple sh
hapes by using g CSS.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Explain ho e new CSS3 co


ow to use the olor value setss.

• Use CSS3 to provide gradients and multi-image


m b
backgrounds.

• Combine CSS3 propertties to create shapes, and use


u simple transforms to manipulate elem
ments on the
page.
6-28 Styling HTML5 by Using CSSS3

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:

• Any of the 147 color keyywords defined


d in the modu
ule. For example, red or gre
een.

color: ye
ellow;

• A red-green n-blue (RGB) model value sspecified in th hree- or six-digit hexadecim


mal notation, a triplet of
integers, orr a triplet of percentage values. Each of tthe three values represents the amount of
o red,
green, and blue is included in the colo or, with valuess for each bettween 0 and 2
255 (0 to 100%
%).

color: #f
ff0; /* #
#rgb */
color: #f
ffff00; /* #
#rrggbb */
color: rg
gb(255, 255, 0);
color: rg
gb(100%, 100
0%, 0%);

• A red-greenn-blue-alpha (RGBA) mode el value speciffied as either a triplet of inttegers, or a triiplet of


percentagee values plus aan opacity valu
ue of between n 0 and 1 whe ere 0 is complletely transparent and 1
is complete
ely solid (opaqque).

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 */

• The keyworrd transparen


nt, which is th
he same value as rgba(0,0,0
0,0).

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

• A hue-saturation-lightness-alpha (HSLA) model value specified as a quadruplet of numbers. The first


three are those of the HSL model and the fourth is the same opacity value of between 0 and 1 as in
the RGBA model.

color: hsla(60, 100%, 50%, 0.2); /* mostly transparent yellow */

• 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

CSSS enables you u to set a varie


ety of backgroound propertties on many eelements. A number of pro operties are
avaailable that en
nable you to specify
s a color for the backkground or an
n image, alongg with how thhat image is
rep
peated (this wwas described in module 2).. In CSS3, therre are two significant addittions to these
po
ossibilities.

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.

No ote that the background shorthand pro


operty also sup
pports multiple images. The
e previous rulle could
alsso be written like this:

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:

• A linear graadient, which h is a gradual change in collor from the start


s color to tthe stop colorr. By
default, the
e start color is displayed at tthe top of the
e background and the end color at the b bottom,
although thhe direction of the gradientt may be chan nged.
Programming in HTML5 with JavaScript and CSS3 6-31

background: linear-gradient(direction, start-color, [mid-color-list,] end-color);

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.

background: linear-gradient(30deg, blue, green, yellow);

• 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.

background: radial-gradient(position, shape, start-color, [mid-color-list,] end-


color);

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.

background: radial-gradient(top right, ellipse, red, blue);

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

In addition to generating gra CSS3 also enables you to ap


aphics by using gradients, C pply graphical
tra
ansformationss such as rotattion and skew
w to any elemeent. By transfo ed and adjacent color
orming stacke
blo
ocks, you can draw a numb ber of shapes simply by usin
ng CSS.

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);

• scale(x,y) : 2d variant off scale3d().

• scaleX(x), sscaleY(y), sca


aleZ(z) : Single axis variantss of scale3d()).
• rotate3d(x x,y,z,a) : Rotattes an elemen
nt in 3d by angle a around the point with
h co-ordinate
es (x,y,z).
Angle a is a value in degrees.

• rotate(a) : Rotates an ele


ement in 2d by
b angle a aro
ound its cente
er.

transform
m: rotate(30
0deg);

• skew(a,b) : Skews an ele


ement by angle a along the
e x-axis and an
ngle b along tthe y-axis. a and
a b are
values in de
egrees betwee
en 0 and 180.

• skewX(a), sskewY(b) : Single axis-variaants of skew(().


Programming in HTML5 with JavaScript and CSS3 6-33

transform: skew(15deg, 15deg);

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

Additional Reading: For an in-depth discussion of 3D transforms in IE10, please read


http://go.microsoft.com/fwlink/?LinkID=267729.

Drawing Shapes by Using CSS3


One of the interesting results of combining height, width, and border values, the before and after
pseudo-elements, and some rotation transforms, are the number of shapes that you can generate simply
by using CSS. For example, to draw a square or rectangle, just use the height and width properties with a
background color:

#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%;
}

You can draw triangles like this:

#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:

• Implement advanced styyling for text elements


e by using CSS

• Style block elements by using


u CSS.

• Create grap
phical elements by using CSSS.

Esttimated Time:: 60 minutes

• Virtual Macchines: 20480A 1-06, MSL-TMG1


A-SEA-DEV11
• User Name: Student

• 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

T main taskks for this exerrcise are as fo


The ollows:

1 Review the HTML Structu


1. ure

2 Style the Naavigation Bar and Links


2.
3 Create Grap
3. phics by Using
g Pseudo Elem
ments

4 Test the Naavigation Bar


4.

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>.

Notice thhat the class of the <nav> element


e is page-nav, and tthat it containns a <div> ele ement with
the class container. Also notice thatt the Home lin
nk has the claass active beccause it is the active page.

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

The navigattion bar lookss like this:

FIGURE 6.5: THE UNS


STYLED NAV
VIGATION BA
AR
7. Close Intern
net Explorer.

X Task 2: Sty
yle the Nav
vigation Barr and Links
1. Open the n
nav.css style sheet in the styyles folder.

2. Modify the style of the n


navigation barr as follows:

• 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.

• Using the nnav.page-nav


v .container selector,
s style the containerr to use the Flexible Box Layyout Model
display style
e.

The navigattion bar should look like th


his:

FIGURE 6.6: THE NAV


VIGATION BA
AR WITH INIITIAL STYLIN
NG
3. Modify the style for the links
l for the n
navigation barr by using the nav.page-na
av a selector, as follows:

• Set the disp


play style to block.
b

• Set the min


nimum width to
t 9rem.
• Set the top and bottom paddings to 0
0, and the leftt and right pad
ddings to 1.8rem.

• Set the textt alignment to


o center.

• Set the link color to #c3cc3c3.


• Add a dotte
ed border on the right of e
each link, using
g the color #3
3d3d3d.

• Add a small, black text sh


hadow.

• Display the text for the liinks in upperccase.


The links in the navigatio
on bar should look like this:

FIGURE 6.7: THE NAV


VIGATION BA
AR WITH STY
YLED LINKS
4. Add a CSS rule
r that displlays a dotted border with the color #3d3 3d3d to the le eft of the first link in the
navigation bar. (Use the first-child psseudo-elemen nt to select the
e first link.)

5. Add a CSS rule


r that applies when a moouse hovers over
o a navigattion link. Make the text colo
or #e4e4e4
and the bacckground colo
or black. (Use the hover psseudo-elemennt.)
Programming in HTTML5 with JavaScrippt and CSS3 6-37
7

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;
}

The navigation bar should look like


e this:

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.

Results: Afterr completing this


R t exercise, you
y will have styled the navvigation bar tto match the design
d
m
mockup.
6-38 Styling HTML5 by Using CSSS3

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:

FIGURE 6.9: THE REG


GISTER LINK IN
I THE HEAD
DER OF THE HOME
H PAGE
Yo
ou will use a sttyle to set the
e position of th
he Register liink. You will m
modify the appearance of the text for
the
e link, add a background
b gradient, rotate the link, and
d add the circcular dotted bborder. Finally,, you will
run
n the applicattion, view the Home page, and verify thaat the Registe er link is similaar to that envvisioned by
the
e designer.

The main tasks ffor this exercise are as follo


ows:

1. Review the HT
TML and CSS

2. Position the R
Register Link aand Set the Te
ext Styling

3. Style the Register Link Backkground, Shape, and Rotattion Properties


4. Test the Regisster Link

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.

2. In the ConttosoConf proj


oject, open the
e index.htm file.
f

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.

5. Run the app


plication, view
w the index.htm page, and
d verify that th
he header’s Re
egister link iss currently
unstyled.
6. net Explorer.
Close Intern

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:

• Use the blo


ock layout model for the Re
egister link an
nd give it a he
eight of 10rem
m and a width
h of 16rem.

• 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. :

The Regisster link shoulld look like this:

FIGUR STYLED REGISTER LINK


RE 6.11: THE S
2
2. Verify thaat the Registe
er link change
es color when the mouse ho
overs over it.

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:

1 Review the HTML and CSSS


1.

2 Define Textt Columns


2.

3 Add a Drop
3. p Cap at the SStart of the Text

4 Indent Para
4. agraphs

5 Style the Block Quote


5.

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.

2. Implement the .about > article > secction CSS rule


e:

• Flow the co
ontent over th
hree columns.

• Add a gap o
of 5rem betw
ween the colum
mns.

• Justify the ttext.

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:

• Use the firsst-letter pseu


udo property tto select the ffirst letter of the text.

• Use the floa


at property to
o make the re
est of the text wrap around the first lette
er.
• Use the ma
argin, line-he
eight, and color properties to match the
e following im
mage:

The first paragraph of texxt should lookk like this:

FIGURE 6.13: THE FIR


RST PARAGR
RAPH ON THE
E ABOUT PAG
GE

X Task 4: Indent Paragraphs


1. In about.csss, add a CSS rule that usess the text-indent property to indent the
e first line of e
each
paragraph bby 3rem.

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:

The quotes should look llike this:

FIGURE 6.14: A STYLED BLOCK QUOTE


• Use a :befo
ore pseudo ele
ement to gen
nerate the larg
ge double quo
otation mark.

• Use the seq


quence '\201C
C' for the quo
otation mark.
Programming in HTTML5 with JavaScrippt and CSS3 6-43
3

• 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.

Test Your Know


wledge

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

You caannot downlo


oad fonts by u
using CSS.

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 

Lesson 1: Writing Well-Structured JavaScript Code 7-3 

Lesson 2: Creating Custom Objects 7-10 


Lesson 3: Extending Objects 7-18 

Lab: Refining Code for Maintainability and Extensibility 7-24 

Module Review and Takeaways 7-30 


7-2 Creating Objects and Methodds by Using JavaScrript

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.

This module desscribes how too write well-sttructured JavaaScript code b


by using languuage featuress such as
namespaces, ob bjects, encapsu
ulation, and in
nheritance. Thhese conceptss might seem familiar if youu have
experience in a language succh as Java or C#,
C but the JavvaScript appro oach is quite different and there are
maany subtleties that you musst understandd if you want tto write mainttainable code.

Ob
bjectives
Aftter completing this module
e, you will be able to:

• Write well-sstructured JavvaScript code..

• Use JavaScrript code to crreate custom objects.

• Implement object-orientted technique


es by using JavvaScript idiom
ms.
Programming in HTML5 with JavaScrript and CSS3 7-3
3

Lesson 1
Writiing We
ell-Strucctured JavaScrript Cod
de

As web appliccations grow in size, it beco


A omes increasin ngly importannt to properly structure you
ur code so
t
that you can m
maintain it mo
ore easily. Thiis lesson will show
s you seve
eral techniquees to help you
u achieve this
g
goal.

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

Sccoping and Hoisting


g

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.

Scoope in JavaScript is subtly d


different from
m scope in C#, C++, or Javaa. Specifically, JavaScript do oes not
suppport the con ncept of blockk-scoped variaables. If you declare a variable inside a b
block, the visib
bility of the
on scope, as iff the variable was declared at the start o
variable is elevaated to functio of the functionn. This
lan
nguage featurre, whereby va ariables declared inside a bblock are eleva
ated to function scope, is known
k as
hooisting.
onstrates how scoping and hoisting workk in JavaScriptt. Note the following
The following exxample demo
po
oints:

• The examplle declares a g


global variable named num
m and assigns it the value 7
7.

• 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

If yyou are familiar with C, C#,, Java, Visual B


Basic, or almo
ost any contem
mporary programming lang
guage, you
will be aware off the concept of using namespaces to avvoid name classhes.

obal name claashes can be a big problem


Glo m in JavaScriptt. Any global variables
v that you declare iin your
code will be acccessible by all the JavaScrippt code in the web applicatiion. Given this fact, it is alm
most
ine
evitable that yyou will sooneer or later define a variable name that clashes with an nother global vvariable, no
maatter how hard d you try to aadopt a namin ng convention n aimed at enssuring the uniqueness of vaariable
names. In additiion, your JavaaScript applicaations may use e third-party libraries that define their oown global
variables, and yoou have little control (if anyy) over how these variabless are named.

JavvaScript provides several m


mechanisms th
hat help you to
o avoid globa
al name clashe
es, including:
• Immediately invoked fun
nctions

• 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

var age = parseInt(ageEnteredByUser);


var height = parseFloat(heightEnteredByUser);
if (isNan(age) || isNan(height))
alert("Invalid input");

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:

• hat contain prroperties and methods.


Create custom objects th

• Use object literal notatio he properties of objects.


on to define th
• n a common set of propertiies to objects.
Define consstructor functions to assign

• Use prototyypes to implem


ment object behavior.
b

• Use the Obj


bject.create() function to create objects based on an e otype.
existing proto
Programming in HTTML5 with JavaScrippt and CSS3 7-11
1

C
Creating S
Simple Ob
bjects

JJavaScript deffines a standard object nam


med Object. Y
You can create
e a new objecct by using the
e following
s
simple syntax:

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.

A simpler wayy to create an object is to u


use braces {}. The
T following example is se
emantically eq
quivalent to
t first example:
the

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;

A property can either hold a data value or refer to a ffunction. If the


e property reffers to a functtion, the
p
property nown as a metthod. Inside a method, the keyword thiss refers to the object upon which the
is kn
m
method was invoked (usually the object containing th he method). T The following example show ws how to
a some datta properties to
add t an existing employee object, and how w to add a me ethod to implement
b
behavior on the object:

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.

Accessing Properties on an Object


To access a property or invoke a method on an object, use the following syntax:

objectReference.propertyName = value;
objectReference.functionName(parameters);

The following example shows how to access data properties and invoke methods on an employee object:

var newSalary = employee1.payRise(1000);


document.write("New salary for employee1 is " + newSalary);
Programming in HTTML5 with JavaScrippt and CSS3 7-13
3

U
Using Objject Literaal Notation

Object literal notation provvides a shorthand way for d


O defining an ob
bject and setting its properrties. Object
l
literal notation has the follo
owing syntax::

var obj
jectName = {
pro
operty1: value1,
pro
operty2: value2,
...
};

T following example sho


The ows how to cre
eate a new ob
bject and define its propertties:

var emp
ployee1 = {
nam
me: "John Smith",
age
e: 21,
salary: 10000
};

You can also define


Y d methods as part of the
t object deffinition. Imple ement each m method inline by using the
s
syntax functioon(){…}. With hin the functio
on, the this keeyword referss to the targett object. The ffollowing
e
example showws how to crea ate an object that containss properties an
nd methods. T The methods reference
p
properties thaat are part of tthe same obje
ect:

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

In JavaScript, a cconstructor is a function thhat assigns prooperties to this object. A co


onstructor in JJavaScript
plaays a similar ro C#, Java, or C++, because iit enables you
ole to a class definition in C u to define a common
c set
of properties for objects of th he same type.
Yo
ou can use a constructor funnction to creaate a new obje ect and initialize its values. The constructtor
nction can takke parameterss to indicate the initial values for propertties of the objject. Inside the
fun
constructor, use
e the this keyw
word to set prroperty valuess on the targe et object.

The following exxample define nt, which assigns propertie


es a constructtor function named Accoun es that
rep
present a bank account:

var Accou
unt = function (id, name) {
this.
.id = id;
this.
.name = name
e;
this.
.balance = 0
0;
this.
.numTransact
tions = 0;
};

Aftter you have defined


d a con
nstructor functtion, you can use the consttructor to creaate a new obje
ect by
usiing the new kkeyword. You can pass paraameters into tthe constructoor function to
o specify the in
nitial values
forr the object. W
When you create an object by using the new keyword d, JavaScript pperforms the ffollowing
ste
eps:

1. It creates a new object.

2. It sets the cconstructor p


property of the
e new object to point to th
he constructorr function.

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.

var acc1 = new Accou


unt(1, "John");
var acc2 = new Accou
unt(2, "Mary");
Programming in HTTML5 with JavaScrippt and CSS3 7-15
5

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.

Prototypes givve you a way to share funcctions between


P n objects creaated by using the same connstructor. All
J
JavaScript objjects, including constructorr functions, haave a special pproperty named prototype e. The
p
prototype is really just anotther object too which you caan assign neww properties and methods; you use it as
a blueprint fo
or creating new w objects. It aautomatically provides a sett of functions and other prooperties that
a inherited ffrom the prottotype of the Object type b
are by using a me echanism know wn as prototyype chaining.
P
Prototype chaaining is descrribed in more detail in the next lesson.

Note: T h as the toString


The prototype of the Objecct type provides useful funcctionality such
method, whicch returns a string representation of an object.
m o

The following example setss the prototyp


T pe on the Acccount constructor function shown in the previous
t
topic. The exa
ample adds methods
m to imp
plement bankk account behhavior:

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:

var acc1 = new Account(1, "John");


var acc2 = new Account(2, "Mary");
acc1.deposit(100);
acc1.display();
acc2.withdraw(50);
acc2.display();
Programming in HTTML5 with JavaScrippt and CSS3 7-17
7

U
Using the
e Object.crreate Method

The Object object has a create() metho


T od that enablees you to create an object b based on an e
existing
p
prototype, and optionally pprovide additiional propertiies. This function enables yo
ou to implem
ment an
e
efficient form of inheritancce based on prototypes.
T general syyntax for the Object.create() method iss as follows:
The

Object.create(prototypeObject, properties
sObject)

• The protootypeObject parameter sppecifies the ob


bject to use ass the prototyp
pe for the new
w object. You
can invokke the Object.getPrototyp
peOf() method if you want to obtain the e prototype off an existing
object to use here.

• The proppertiesObjectt parameter is optional, and


d specifies an object whose
e properties w
will be added
into the n
new object.
T following example crea
The ates an objectt by using a n
null prototype
e, and adds tw
wo properties:

var obj
j1 = Object.create(null, { prop1 = "hello", prop2 = "world
d" });

Note: Iff you do speciify a null prototype, the on


nly functionalitty available in
n the new obje
ect
will be that de
w efined by the properties ob bject. This meaans that meth
hods normallyy inherited froom
O
Object, such aas toString and the + operator, will nott be available.

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

Moost object-oriented languages are basedd on the conce


ept of classes,, but JavaScrip
pt does not usse classes.
In JavaScript, evverything is an
n object.

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.

The following example sho


T ows how to use closures to achieve encap
psulation. The
e name and a
age variables
a effectivelyy private to Pe
are erson objects, whereas the getName(), getAge(), setName(), andd setAge()
m
methods are public.
p

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"

Note: JavaScript also provides accessor properties enabling a programmer to encapsulate


data behind get and set functions by using the Object.defineProperty function. Property
accessors also support patterns such as read-only properties. For more information, visit
http://go.microsoft.com/fwlink/?LinkID=267730.
Programming in HTTML5 with JavaScrippt and CSS3 7-21
1

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.

Note: A prototype ha as a reference


e to the constructor with which it is assocciated. If you
don't set the constructor
d c p
property of thhe derived proototype to thee derived consstructor, it willl
c
continue to re
eference the bbase constructtor, which ma ay cause problems later when your JavaSScript
c
code needs to o resolve referrences to prop
perties in the derived class..

T following example sho


The ows how to im
mplement inhe
eritance in JavvaScript by usiing prototype
e chaining.

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

You can use p


Y prototypes to extend the fuunctionality off existing obje
ects, including
g the built-in o
objects
d
defined as part of the stand
dard JavaScrip
pt language.

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.

The following example sho


T ows how to ad dd functionalitty to an existing object. The
e code definees a
c
constructor fu
unction named Point, to re epresent a coo
ordinate pointt that has x an nd y propertie
es. The code
t
then adds me ethods named d moveBy() and moveTo()) to the prototype object fo or Point, and shows how
t
these method ds are available on all Pointt objects.

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:

• Implement good practice


es for writing JavaScript co
ode.

• Refactor JavvaScript code to use objectt-oriented principles.


Esttimated Time:: 60 minutes

• Virtual Macchines: 20480A 1-07, MSL-TMG1


A-SEA-DEV11

• User Name: Student


• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 7-25

Exercise 1: Object Inheritance


Scenario
In this exercise, you will create a utility function named Object.inherit. The purpose of this function is to
define a prototype object and initialization function, which can then be used to create new instances of a
type.

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.

Using a Prototype to Initialize an Object


var Circle = Object.inherit({
initialize: function (radius) {
this.radius = radius;
},
area: function () {
return Math.PI * this.radius * this.radius;
},
circumference: function() {
return 2 * Math.PI * this.radius;
}
});
// Create and use a Circle object
var c = Circle.create(10);
alert(c.area());
alert(c.circumference());

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.

The main tasks for this exercise are as follows:

1. Review the Object.inherit.js JavaScript File

2. Implement the Inherit Function

3. Scope the JavaScript Code Inside an Immediately Invoked Function Expression

4. Use Strict Mode

X Task 1: Review the Object.inherit.js JavaScript File


1. Start the MSL-TMG1 virtual machine if it is not already running.

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.

4. Open the Object.inherit.js file in the scripts folder.


5. Review the JavaScript code and comments in this file. This file contains two functions called
copyOwnProperties and inherit.

• 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.

X Task 2: Implement the Inherit Function


1. Implement the inherit function, using the TODO comments for guidance.

• 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.

• Copy the properties of additionalProperties into factory.


• Return the value of factory from the inherit function.

2. Complete the implementation of the factory.create method in the inherit function:

• Create a new object that uses factory as its prototype.


• Call the initialize method of the new object (if it exists), passing any arguments that were passed to
create.

• Return the new object from the create function.

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.

X Task 3: Scope the JavaScript Code Inside an Immediately Invoked Function


Expression
1. In the Object.inherit.js file, enclose the JavaScript code in an immediately invoked function
expression.

X Task 4: Use Strict Mode


1. In the Object.inherit.js file, modify the immediately invoked function to use strict mode.

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

Exercise 2: Refactoring JavaScript Code to Use Objects


Scenario
The JavaScript code for the Schedule page has been partially refactored to be more maintainable. In this
exercise, you will continue the refactoring process by updating the code for the Schedule page. You will
use the Object.inherit utility function to define a ScheduleList prototype object. Then you will move the
existing functions and variables relating to the schedule list into this prototype.

The main tasks for this exercise are as follows:


1. Define the ScheduleList Factory

2. Convert Functions Into Methods of the ScheduleList Object

3. Create and Use a ScheduleList Object


4. Test the Application

X Task 1: Define the ScheduleList Factory


1. Open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.

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).

X Task 2: Convert Functions Into Methods of the ScheduleList Object


1. In the schedule.js file, find the following comment:

// TODO: Refactor these functions into methods of the ScheduleList object.

2. Convert each of the functions following the comment into methods of ScheduleList.

Note: As an example of refactoring a function, the following code:


downloadDone: function (responseData) {
addAll(responseData.schedule);
}
Should be moved to the ScheduleList object and converted to:
var ScheduleList = Object.inherit({
initialize: function (element, localStarStorage) {
...
},
...
downloadDone: function (responseData) {
this.addAll(responseData.schedule);
},
...
}
7-28 Creatingg Objects and Methods by Using JavaSccript

3. In the starttDownload fu unction, add tthe context o


option to the o
object passed to the ajax fu
unction
and initializze it to this.

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 3: Crreate and Use a Schedu


uleList Obje
ect
1. Near the en
nd of the sche
edule.js file, find
f the follow
wing JavaScrip
pt code:

// TODO: Replace the


e following code by cre
eating a Sche
eduleList ob
bject
// and calling
g the startD
Download met
thod.
element = document.g
getElementBy
yId("schedule");
localSta
arStorage = LocalStarSto
L orage.create
e(localStorag
ge);
startDow
wnload();

2. Modify this code to creatte a Schedule


eList object, p
passing it the DOM elemen
nt and local staar storage
object.
3. Call the startDownload method of th
he ScheduleList object.

X Task 4: Te
est the Appllication
1. Run the app
plication and view the sche
edule.htm pa
age.

2. Verify that tthe page lookks similar to th


he image belo
ow:
The Schedu
ule page should still displayy the list of sesssions for the conference, like this:

FIGURE 7.1: THE SCH


HEDULE PAGE
E
Programming in HTML5 with JavaScript and CSS3 7-29

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.

3. Close Internet Explorer.

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?

Test Your Know


wledge

Q
Question

W
Which of the ffollowing statements is tru
ue?

S
Select the corrrect answer.

JavaSccript uses the public, private


e, and protectted keywordss to implemen
nt
encapsulation.

JavaSccript does nott support encaapsulation.

JavaSccript uses closures to achievve encapsulattion.


Programming in HTML5 with JavaScript and CSS3 7-31

Question

JavaScript uses prototype chaining to achieve encapsulation.

JavaScript uses the Object.create() function to implement encapsulation.


 
8-1

Module 8
Creating Interactive Pages by Using HTML5 APIs
Contents:
Module Overview 8-2 

Lesson 1: Interacting with Files 8-3 

Lesson 2: Incorporating Multimedia 8-10 


Lesson 3: Reacting to Browser Location and Context 8-17 

Lesson 4: Debugging and Profiling a Web Application 8-24 

Lab: Creating Interactive Pages with HTML5 APIs 8-31 


Module Review and Takeaways 8-39 
8-2 Creating Interactive Pages byy Using HTML5 APIss

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.

This module desscribes how to


o create interaactive HTML5
5 web applicattions that can
n access the lo
ocal file
sysstem, enable the
t user to drrag-and-drop data onto eleements in a w
web page, playy multimedia ffiles, and
ob
btain geolocattion information.

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.

• Play video aand audio file


es in a web page, without th
he need for plugins.

• 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:

• Describe the HTML5 file types.

• Describe the FileReade


er interface fo es on the local file system.
or reading file
• Use FileR
Reader to read
d a text file.

• 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

HT TML5 has a staandardized File API that en


nables an HTM
ML page to intteract with loccal files on the
e browser
e system. This API defines four key interffaces:
file

• 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 name aattribute indiccates the nam


me of the file w on, expressed as a string.
without any paath informatio
• The lastMo
odifiedDate attribute
a indiccates the last m
modification d
date of the file
e, expressed aas a Date
object.

• 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.

• Implement drag-and-dro op support in your web pag ge, by handlin


ng the drop e event on an ellement.
When the user
u drops file
es on the elem
ment, the drop
p event indicates the files th
hat the user d
dropped
onto the ele
ement.

Additionaal Reading: FFor detailed in


nformation ab
bout the HTML5 File API, se
ee
htttp://go.microssoft.com/fwlin
nk/?LinkID=26 67731.

• 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

• readAsTe nd makes the contents available as plain


ext() reads a file or blob an n text. This me
ethod is useful
if you want to read the
e contents of a text file.

• 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.

A FileReaderr object reads contents asyn nchronously, and


a fires even nts to indicate
e the progresss of the
l
loading operaation. The follo
owing list desscribes the eve
ents that you typically handdle:

• 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().

• The aborrt event indicaates that data loading has b


been aborted, perhaps due
e to a call to th
he abort()
method.

• The errorr event indicates that an errror occurred during loadin


ng. Errors can occur for seve eral reasons,
such as atttempting to read an unreaadable file, atttempting to rread a file thatt is too large, or
attemptinng multiple sim
multaneous re eads on the saame file.

• The loadeend event ind


dicates that th
he read operation has comp
pleted, either successfully o
or
unsuccesssfully.
8-6 Creating Interactive Pages byy Using HTML5 APIss

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

The FileReader readAsDattaURL() meth


T binary file on the local file system. The
hod enables yyou to read a b
f
following example shows h
how to read an
n image file.

The web page


T e includes an <input> elem ment that enaables the user to select an image file on tthe local file
s
system. As soo
on as the userr selects the fiile, the onLoa
adBinaryFile(() function reaads the file an
nd assigns its
c
contents in an
n <img> elem ment on the w web page.

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:

• Set the draggable attrib


bute for the element to true
e.

• Handle the dragstart evvent.

• 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.

The DataTransffer object deffines attribute


es and method
ds that enable
e you to contrrol all aspects of the
dra
ag-and-drop operation:

• setData(mimeType, datta) specifies tthe MIME type


e of the data being transferred, and the data itself.

• setDragImage(imgElem ment, x, y) specifies a custo


om mouse currsor image that the browse
er will use
during the drag-and-dro
op operation.

• 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.

The following exxample showss how to makke a <div> ele


ement dragga
able:

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.

Dropping Content on a <div> Element


<div ondragover="handleDragOver()" ondrop="handleDrop()"></div>
<script type="text/javascript">
function handleDragOver(event) {
event.preventDefault();
}
function handleDrop(event) {
event.target.innerHTML = e.dataTransfer.getData("text/html");
}
</script>
8-10 Creatingg Interactive Pages by Using HTML5 APPIs

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

• Interact witth a video in code.


c
• ow to play aud
Describe ho dio files.
Programming in HTTML5 with JavaScrippt and CSS3 8-11
1

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>

T source off a video can b


The be a local file or a reference
e to a resourcce on a remote URL.

The <video> tag also supp


T ports the follo
owing attributtes, which ena
able you to cu
ustomize the b
behavior and
a
appearance o
of the video pllayer on the w
web page:

• The width and heightt attributes en


nable you to specify the size o player on the web page,
e of the video
in pixels.

• The poste er attribute enables you to


o specify an immage to be dissplayed on the web page while
w the
video is b
being downloa aded, or until the user pressses the play b
button.

• 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.

• The loop Boolean attriibute specifiess that the vide


eo will start over again as ssoon as it has finished
playing.
• ed Boolean atttribute speciffies that the audio output ffor the video will
The mute w be muted
d.

T following example sho


The ows how to use the <video
o> tag attributtes.

This example creates a vide


T eo player thatt is 300 pixels wide and 200
0 pixels high. A
An image nam med
"
"MyPoster.jpg
g" will be disp played while thhe video is beeing downloadded. As soon aas the video h has been
d
downloaded, it will start plaaying immediiately with the e audio muted
d. The video pplayer will disp play controls
t enable the user to contrrol the video p
to player. As soon as the video
o has finished, it will restartt
a
automatically .
8-12 Creating Interactive Pages by Using HTML5 APIs

Creating a Video Player


<video src="MyVideo.mp4"
width="300" height="200"
poster="MyPoster.jpg"
autoplay muted controls loop />
Programming in HTTML5 with JavaScrippt and CSS3 8-13
3

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:

• The src attribute specifies a video so


ource.

• The type attribute spe


ecifies the vide
eo MIME type
e, such as vide
eo/mp4, video
o/webm, and vvideo/ogg.

IIf you includee multiple <soource> tags wwithin a <vide


eo> tag, the video
v player w
will play the firrst video
f
format suppo orted by the browser. You ccan also embeed Microsoft Silverlight®
S or Adobe® Flaash content ass
a fallback, plu
us a simple texxt message for browsers that do not sup
pport the <vid deo> tag.

T following example sho


The ows how to cre
eate a video p
player that sup
pports multip
ple types of co
ontent.

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

Yoou can create <video> elem


ments program
mmatically byy using Docum
ment Object Model
M (DOM) functions
in JavaScript cod
de.

The following JaavaScript code


e creates a vid
deo object, se
ets its attributtes, and then adds
a it to an existing
e
ele
ement on the web page.

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:

• The play() function playss the video.

• The pause(() function pauses the video


o.

• The paused dicates whether the video is currently pa


d property ind aused.

• The currentTime properrty gets and sets the curren


nt time in the video.

• 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.

• The playba ackRate propeerty gets and sets the playb


back rate of th
he video. A pllaybackRate of 1
indicates no
ormal speed.

The following exxample plays a video if it iss paused, or p


pauses a video g. The example also
o if it is playing
dissplays the time and duratio
on of a video before
b it startts playing.
Programming in HTML5 with JavaScript and CSS3 8-15

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.

Handling Video Events


aVideo.addEventListener("loadedmetadata", function() {
alert("Video duration: " + aVideo.duration);
},
false);
aVideo.addEventListener("loadeddata", function() {
aVideo.play();
},
false);
aVideo.addEventListener("timeupdate", function() {
alert("Video current time: " + aVideo.currentTime);
},
false);
8-16 Creatingg Interactive Pages by Using HTML5 APPIs

Pllaying Aud
dio Conte
ent by Using the <aaudio> Tag

HT play audio natively in a web


TML5 provides the <audio> tag that enables you to p b page, witho
out the
eed for plugins.
ne

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

There are other similarities be


etween the <audio> and <
<video> tagss:
• The <audio
o> tag supports the <sourrce> child tag
g, to enable yo
ou to provide alternative au
udio file
formats.

• 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

IIn this lesson, you will learn


n how to use the
t HTML5 Ge eolocation APPI to determin
ne the currentt location of
t browser. Y
the You will also ssee how to use the Page Visibility API an
nd properties o
of the naviga
ator object in
t DOM to o
the obtain informa ation about th
he context in which a web page is runnin ng.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Describe the HTML5 G


Geolocation AP
PI.

• Request g
geolocation in
nformation.
• Process g
geolocation information.

• Handle geolocation errors.

• 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.

• Tracking the movement of a user to se


ee how far the
ey have travelled in a certaain time period.
The HTML5 specification doe es not stipulatte a particular mechanism ffor obtaining geolocation information.
Insstead, when a web applicattion makes a g geolocation re PI interacts wiith underlying
equest, the AP g device
capabilities to re
etrieve the infformation. The device can u use any of the
e following te
echniques to determine
d
loccation:

• IP address. The user's IP address is loo


oked up, and tthe physical address of the registrant is rretrieved.
This is a rud
dimentary technique that ccan be very inaaccurate.
• GPS positio oning. This tecchnique is pop
pular on mobile devices, annd involves recceiving GPS d
data from
satellites to determine th he location of the device. This technique can be very aaccurate, but it can be
slow and it might not wo ork when the device is indooors.

• based on the user's distance from a


Wi-Fi. This ttechnique invvolves triangulating the devvice location b
number of known Wi-Fi access points. This technique can be verry accurate in urban areas, where
there are a lot of Wi-Fi access points in the vicinity.
• Cell phone location. Thiss technique involves triangu ulating the de
evice location based on thee user's
distance fro
om a number of known cell phone towers. This techniique is relative ely accurate in
n urban
e a device that has access to
areas, but itt does require o a cell phone
e or wireless m
modem.
• User-define
ed location infformation. An n application ccan ask the usser to enter th
heir address, postal
p code,
or some othher details thaat the application can use tto provide loccation-aware services.
s This ttechnique
can be usefful if the user is able to supply more accu urate location
n data than otther technique es.
Programming in HTTML5 with JavaScrippt and CSS3 8-19
9

R
Requestin
ng Geolocation Info
ormation

T HTML5 G
The Geolocation AP
PI supports tw
wo types of po
osition requesst:

• One-shott position requ


uest. To perfo
orm a one-sho
ot position req
quest, invoke the
navigato
or.geolocatio on.getCurrenttPosition() m
method.

• Repeatedd position upd


dates. To start receiving possition updatess, invoke the
navigatoor.geolocatioon.watchPosittion() method d. This metho
od returns a w watch ID value. To stop
receiving position updates, invoke navigator.geo
n olocation.cleearWatch(), aand pass the w watch ID as a
paramete er.

T getCurre
The entPosition() and watchPo
osition() methods take the
e following pa
arameters:

• A call-bacck function, which


w will be called
c by the bbrowser when n location dataa is available. In the case off
getCurreentPosition(),, the call-backk function willl be called once. In the case
e of watchPo osition(), the
call-back function will be called repeeatedly until you
y invoke cle earWatch().

• 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.

o maxiimumAge. Ho ow old locatio


on data can b
be in milliseconds, before th
he browser must try to
The default value for the maximumAge property is ze
refressh the data. T ero seconds.

The following example sho


T ows how to ma
ake a one-offf request for ggeolocation in nformation. Th
he example
r
requests the h
highest accuraacy informatio
on available, aand specifies tthat the inform
mation must b
be available
w
within 5 secon
nds, or it will time
t out.
8-20 Creating Interactive Pages by Using HTML5 APIs

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.

var watchID = navigator.geolocation.watchPosition(myPositionCallbackFunction,

myPositionErrorCallbackFunction,

{enableHighAccuracy: true, maximumAge: 10000} );

The final example shows how to stop receiving geolocation information.

navigator.geolocation.clearWatch(watchID);
Programming in HTTML5 with JavaScrippt and CSS3 8-21
1

P
Processing
g Geoloca
ation Information

When geolocaation informaation is availab


W ble, the browsser calls the caall-back function that you sspecified
w
when you invo
oked getCurrrentPosition(() or watchPo osition(). Thee call-back funnction receives an object
t
that has a coo
ords propertyy, which has th
he following p
properties to provide
p coord
dinate informa ation:
• latitude, in degrees. A latitude of 0 degrees represents the equator. A posittive latitude in
ndicates a
location in the Northern Hemispherre, and a negaative latitude iindicates a loccation in the Southern
S
Hemisphe ere.

• longitude, in degrees.. A longitude of 0 degrees represents the


e Greenwich M Meridian. A positive
longitude
e indicates a lo
ocation east o dicates a location west of
of Greenwich, and a negativve latitude ind
Greenwicch.
• accuracy
y, in meters.

The coords property also h


T has the follow
wing paramete
ers, which mig t device is incapable of
ght be null if the
d
determining tthe values:
• altitude, in meters abo
ove sea level.

• altitudeA
Accuracy, in m
meters.

• heading, in degrees re
elative to the North directio
on.

• speed, in
n meters/secon
nd.

T following example sho


The mplement a call-back function for geoloccation informaation:
ows how to im

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.

• message: A string that id


dentifies the rreason for the
e error.
The following exxample showss how to impllement an erro
or call-back fu
unction for ge
eolocation infformation

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-bbased email cclient is visible


e, it might che
eck the server for new mail every few secconds. When
hidden, itt might scale cchecking emaail to every few w minutes.

• If a web-b
based puzzle game is hidde
en, the game could be pau
used until it be
ecomes visible
e again.

T Page Visibility API conssists of two prroperties and an event:


The
• The docu
ument.hidden
n property de
escribes wheth
her the page iis visible or no
ot.

• 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

In this lesson, yo ng API to evaluate the netw


ou will learn aabout the Navvigation Timin work performaance of a
weeb page.

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

In this demonstration, you wiill see how to use the F12 D


Developer Too
ols to view and debug JavaaScript code
in a live web application.

De
emonstration Steps
Sett a Breakpoint in JavaScriptt code

1. ndows 8 Start screen, click the Desktop tile.


On the Win

2. On the Win
ndows taskbarr, click Interne
et Explorer.

3. In Internet Explorer, brow


wse to the file
e E:\Democod
de\Documen
nt.html.

4. If the messaage Internet Explorer


E restricted this webpage from running scripts or ActiveX co
ontrols
appears, click Allow blocked content.
5. o display the menu bar.
Press F10 to

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.

es the F12 Devveloper Tools to appear in a standalone window.


Note: Thiss action cause

8. In the F12 D ols window, click Script.


Developer Too

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.

3. In Internet Explorer, brow


wse to the we
ebsite http://w
www.beautyo
oftheweb.co
om/.
4. o display the Internet
Press F10 to I Explo
orer menu barr.

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.

8. In Internet Explorer, clickk the for deve


elopers link.

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 Response heade


13. ers.
1 Click Response body.
14.

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:

FIGURE 8.3: PROFILE


E DATA FOR A WEB PAGE
E
6. On the F12 Developer To
ools toolbar, in the Currentt view list, clicck Call tree.
7. In the Searcch Profiler bo
ox, type onre
eadystatechan
nge and then
n press Enter.

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:

• Conference speakers nneed a way to generate the eir badges. A w


web page sho ould be added
d that enables
a speakerr to drag-and-drop a profile picture to start creating their
t badge.
• A video from a previou
us conference
e is available. T
This video sho
ould be available on the Ho
ome page.

• The Locattion page sho


ould be custom
mized to display informatio
on about the visitor’s
v curren
nt physical
location.

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

Exercise 1: Dragging and Dropping Images


Scenario
In this exercise, you will begin working on the Speaker Badge page. This page will eventually enable
conference speakers to create a badge displaying their name, photo, and ID barcode. In this exercise, you
will implement drag-and-drop support so that an image of a speaker can be dropped onto the web page
and displayed.

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.

The main tasks for this exercise are as follows:


1. Review the HTML Markup and JavaScript Code for the Speaker Badge Page

2. Add Drag-and-Drop Event Listeners

3. Handle the Drop Event


4. Read the Image by Using a FileReader

5. 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.

X Task 2: Add Drag-and-Drop Event Listeners


1. In the speaker-badge.js file in the initialize function, add event listeners for the dragover and drop
events of the element variable that call the handleDragOver and handleDrop methods. Ensure that
the correct value of this is used when the handleDragOver and handleDrop methods are called.

Note: The element variable contains a reference to the <img> element that displays the
speaker's image.

X Task 3: Handle the Drop Event


1. In the speaker-badge.js file, find the handleDrop function. Notice that the event that invoked the
function is passed in as the parameter.

2. In this method, add code to perform the following tasks:


o Create a variable containing the array of files from the dataTransfer property of the event.
Programming in HTML5 with JavaScript and CSS3 8-33

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.

• Start reading the first file by calling the readFile function.

Note: The readFile function is not yet complete. You will implement the missing parts of
this function in the next task.

• When this operation is complete, call the displayImage function.

o If a non-image file was dropped, display an alert with the following message:

Please drop an image file.

X Task 4: Read the Image by Using a FileReader


1. In the speaker-badge.js file, review the readFile method.

2. use the File API to implement the missing functionality in the readFile method:

o Create a new FileReader object and assign it to a variable named reader.


o Assign a callback function to the onload property of the reader object.

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.

X Task 5: Test the Speaker Badge Page


1. Run the application and view the speaker-badge.htm page.

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.

4. Close Internet Explorer and File Explorer

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

Exercise 2: Incorporating Video


Scenario
In this exercise, you will add a video to the website Home page. You will add custom controls that enable
a user to play and pause the video, and then you will handle video events to display how much playback
time has elapsed. Finally, you will run the application, view the Home page, and verify that it plays the
video correctly.

The main tasks for this exercise are as follows:


1. Add a Video Player to the Home Page

2. Add Controls to the Video Player

3. Control the Video by Using JavaScript Code


4. Display the Video Elapsed Time

5. Test the Video Player

X Task 1: Add a Video Player to the Home Page


1. Open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.
2. Open the index.htm file and find the following comment:

<!-- TODO: Add video tag here -->

3. Add a <video> element, using the video source specified in the index.htm file.

X Task 2: Add Controls to the Video Player


1. In the index.htm file after the <video> element, add a <div> element with the class video-controls
and a style of display-none. This <div> element should contain two buttons; Play and Pause. Set
the class of the Play button to video-play and set the class of the Pause button to video-pause.

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.

X Task 3: Control the Video by Using JavaScript Code


1. The custom video control elements are hidden when the page initially loads. Open the video.js file in
the scripts\pages folder and review the code in this file.
2. Complete the ready function to display the video control elements (use the block style). The video
controls are available in the controls variable.

3. Near the bottom of the file, add an event listener for the loadeddata event of the video, which calls
the ready function.

4. In the video.js file, complete the play and pause functions.

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

Note: The video variable holds a reference to the video player.


Display or hide a control by setting the style.display property of the control.

5. Add click event listeners for the play and pause buttons, which call the play and pause functions,
respectively.

X Task 4: Display the Video Elapsed Time


1. Complete the updateTime function, to display the elapsed time of the video in the time DOM
element.

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.

X Task 5: Test the Video Player


1. Run the application and view the index.htm page.

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.

4. Click Pause and verify that the video pauses.

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

Exercise 3: Using the Geolocation API to Report the User's Current


Location
Scenario
In this exercise, you will modify the Location page to react to the current geographic location of the user
viewing the page.

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.

The main tasks for this exercise are as follows:


1. Review the HTML Markup and JavaScript Code

2. Get the Current Location of the User Viewing the Page

3. Display the Distance to the Conference Venue


4. Test the Location Page

X Task 1: Review the HTML Markup and JavaScript Code


1. Open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 3 folder.

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:

// TODO: Get current position from the geolocation API.

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.

X Task 3: Display the Distance to the Conference Venue


1. In the location.js file, complete the updateUIForPosition function:

o Create a variable named distance


o Use the distanceFromConference function to calculate the distance to the conference venue.
This function requires the coordinates of the user's current location as a parameter.

X Task 4: Test the Location Page


1. Run the application and view the location.htm page.
8-38 Creating Interactive Pages by Using HTML5 APIs

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.

Question n: What metho ded by the FileReader inte


ods are provid ding files on the
erface for read
local file system?
s

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?

Questionn: What methoods are provid


ded by the na
avigator.geolocation obje
ect for obtainiing
geolocation informatio
on?

V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.

Statement Answer

The F12 Devveloper Toolss require that you have Visu


ual Studio insttalled on
your compuuter before yo
ou can use the em to debug JJavaScript codde. True or
False?
 
9-1

Module 9
Adding Offline Support to Web Applications
Contents:
Module Overview 9-2 

Lesson 1: Reading and Writing Data Locally 9-3 

Lesson 2: Adding Offline Support by Using the Application Cache 9-14 


Lab: Adding Offline Support to Web Applications 9-21 

Module Review and Takeaways 9-27 


9-2 Adding Offline
O Support to Web
W Applications

Modu
ule Ove
erview

Weeb applicationns have a dep


pendency on b being able to connect to a network to fe etch web page es and data.
Ho
owever, in somme environme ents a networkk connection may be interm mittent. In the
ese situations,, it might
be ning by using data cached on the user's device.
e useful to enaable the appliccation to conttinue function
HT
TML5 provides a choice of n new client-sid
de storage opttions, includin
ng session stoorage and locaal storage,
and a resource ccaching mech hanism called the Applicatio on Cache.

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:

• ocally on the user's device, and access th


Save data lo his data from a web applicaation.
• Configure a web applicattion to suppo
ort offline ope
erations by usiing the Appliccation Cache.
Programming in HTML5 with JavaScrript and CSS3 9-3
3

Lesson 1
Read
ding and
d Writing Datta Locallly

One key strate


O egy that a we eb application can use to caache data is too store it locally in the file ssystem of the
u
user’s new strategy, and it has forrmed the basis of several m
device. This is not a n mechanisms ussed by web
s
servers to simulate user sesssions. This lessson describess some of the technologiess that are currrently
a
available.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Explain ho plication can u


ow a web app use cookies to
o maintain sim
mple state info
ormation.

• Use the SSession Storag


ge API to save session state information in
i a web application.

• Use the LLocal Storage API to persist information between sessiions.

• Use storage events to notify an application of cha


anges made tto stored dataa.

• Describe how the Inde


exed Database
e API can implement a strucctured data sttore on the usser's device.
9-4 Adding Offline
O Support to Web
W Applications

M
Maintaining
g Session State Info
ormation by Using Cookies

At their best, we eb application


ns are statelesss, meaning th hat a web servver has no nottion of a continuous
clie
ent session. WWhen a user co onnects to a w website, the wweb server simmply serves the e page requessted by the
useer's browser. IIf the user vie
ews another paage, the web server retrieves that page and a sends it to the user's
broowser. As far aas the web se erver is concerrned, the two requests are ccompletely in ndependent. T This
me echanism can pose a problem if the seco ond page requ uires data thaat the user enttered on the ffirst. To
faccilitate the seaamless connecction among w web pages, th he browser ne eeds a mechan nism to store
infformation rep presenting the e state of the cclient's session
n. The browse er can transmiit this data as part of any
reqquest to view a page in the e website so th hat the serverr can associatee the page req quest with data
preeviously enterred by the use er. This is the basic premise e behind the ccookie protoco ol.

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 ){
...
}

Session storage associates each item of sesssion data witth a unique ke


ey value; you provide this kkey value
whhen you store a value, and use this same
e key value to retrieve the ddata. The Session Storage A
API provides
thrree ways to sttore and retrie
eve data:

• 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 :

var listDiv = document.getElementById("myList");


for( int i=0; i<sessionStorage.length; i++)
{
listDiv.innerHTML += "<br />" + sessionStorage.key(i);
}

To remove an item from session storage, use the removeItem() method.

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

Local Storage allso enables yoou to store daata items on th


he client brow
wser, but unlikke session storrage, items
in local storage are persisted even after the browser sesssion has endeed. The data is stored in the e file
sysstem of the deevice running
g the browser. It is removedd when the we eb application n deletes it, orr when the
useer requests th
hat the browseer removes it. This mechanism is browser-dependent.

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 ){
...
}

The Local Storag


ge API is very similar to the
e Session Storage API. You can store andd retrieve dataa by using
the
e setItem() and getItem()) functions, a name-pair
n keyy, or pseudo-properties.

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:

var listDiv = document.getElementById("myList");


for( int i=0; i<localStorage.length; i++)
{
listDiv.innerHTML += "<br />" + localStorage.key(i);
}

To remove an item from the store, call the removeItem() function:

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

The storage APII to which botth session andd local storage


e conform inccludes a singlee event called storage.
Yo
ou can use thiss event to nottify a web pag
ge of changess to data held in the store; iit fires whenevver data is
moodified.
The following exxample showss how to subsscribe to this e
event:

function myStorageCa
allback( e ) {
alert
t("Key:" + e
e.key + " changed to " + e.newValue
e);
}
window.ad
ddEventListe
ener("storage", myStorag
geCallback, true);

The event objecct passed to th


he event hand
dler includes tthe following properties:

• key: The na
ame of the value which hass changed.
• oldValue: T
The original vaalue before th
he change.

• newValue: The new valu


ue.

• url: The doccument whose script is the origin of the event.


• storageAre
ea: A referencce to the store
e that has changed (session
n or local).

The event mode el enables web pages to listten for storag


ge events and to update the emselves whe en data they
usee from the sto
ore changes their state. Forr example, in Internet
I Explo
orer, if you havve the same w
web page
oppen in multiplee tabs, the data on each tab tabs can remmain synchronized in order to reduce th he scope for
incconsistencies ccaused by chaanges made in different tab bs.

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.

Reader Aid: For more information aabout handling storage eve


ents, visit
htttp://go.microssoft.com/fwlin
nk/?LinkID=26
67735.
Programming in HTTML5 with JavaScrippt and CSS3 9-11
1

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:

var db; // Reference to the daatabase to use


u
var ope
enRequest = indexedDB.oppen("contoso
oDB");
openReq
quest.onsuccess = funct tion(event) {
db = event.target.result;
};
openReq
quest.onerror = functionn(event) {
ale
ert("Error " + event.tarrget.errorCo
ode + " occurred while o
opening the
databas
se");
};

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:

var tx = db.transaction(); // Start a new transaction


var deleteRequest = tx.attendeeStore.delete("1"); // Remove the details for Rachel
Valdez
deleteRequest.onsuccess = function(event) {
// Attendee was successfully deleted
}
deleteRequest.onerror = function(event) {
// Handle failure
};

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

The session storrage, local sto


orage, and InddexedDB APIs provide a pro ogrammer-cen ntric model foor storing
and managing d data locally onn a user's devvice. In additio
on, HTML5 feaatures a mech hanism for cacching web
pages and other resources so o that once thhey are downlo oaded to the client machin ne, the browse er defers to
thiis cache and n
not the netwo ork. After the page
p is downloaded, there is no need to o retrieve it ag
gain. This
savves on networrk resources, and
a enables developers
d to build web appplications thaat do not even n need web
e fact that a web page or otther resource is cached is transparent
connectivity oncce they are cliient-side. The
to the JavaScrip
pt code runnin ng on a web p page, although h the Applicattion Cache APPI includes funnctions and
ob
bjects that enaable JavaScrippt code to dete ect whether a page is runn ning online or offline, and to o refresh
thee cached reso
ources if a netwwork connecttion is available.

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:

• Configure tthe application cache.


• Detect the sstate of the application cacche.

• Refresh the application cache.


c

• Test for nettwork connecttivity.


Programming in HTTML5 with JavaScrippt and CSS3 9-15
5

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.

The cache maanifest file spe


T ecifies the dataa that the web
b browser sho ould retain in the applicatio
on cache. Thiss
f is a list of resources divided into sepaarate sectionss labeled CAC
file CHE, NETWOR RK, and FALLBACK. The
i
information in
n these sections determines how the bro owser respond ds when a request is made for a
r
resource when n the web app online or offline states.
plication is running in the o

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

T file should have the .m


This manifest file exxtension.

Note: T The .manifestt extension file e is of a new M


MIME type called text/cach he-manifest
m
manifest. Youu may need to o configure th
he web serverr to serve this type of file byy adding this new
M
MIME type, if it is not alreaady set up.
9-16 Adding Offline Support to Web Applications

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

The contents of the applicaation cache arre managed b


T by the browser by using thee configuratio
on specified in
n
t cache manifest file. How
the wever you can monitor thee application cache
c from JaavaScript code
e by using thee
A
Application Cache API.
on cache is accessible to JavvaScript code
The applicatio
T e through the applicationC Cache propertty of the
w
window object. The appliccation cache o
object returneed by this prop
perty introducces a comprehhensive eventt
m
model coverinng the lifecyclle and behavior of the cach
he. These evennts include the following:

• checking
g: This event fiires when the browser exam
mines the app
plication cache
e for updates.

• downloaading: This eve


ent fires when
n the browserr starts downlo
oading resourrces to the ap
pplication
cache.
• updatere
eady: This eve
ent fires when
n the new verssion of the cacched objects for
f a web pag
ge have been
download
ded.

• obsoletee: This event fires if the man


nifest file is no
o longer availaable and the aapplication ca
ache is no
longer vaalid for the current web pagge.

• cached: T
This event fire
es when the ap
pplication cacche is ready an
nd available for use.

• error: This event fires if


i an error occcurs while dow
wnloading ressources to cacche, or when cchecking for
resourcess to download d.

• noupdate: This event ffires if no chaanges were fou


und after checking the manifest for upd
dates.

• progresss: This event fiires as each re


esource speciffied in the maanifest is down
nloaded to the application
cache.

T following example sho


The ows how to catch the error event of the application caache:

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:

Status Meaning Description

0 UNCACHED The page is not associated with a cache. No resources


have been downloaded

1 IDLE All cached resources have been downloaded. The


cached event has been fired.

2 CHECKING The cache is being checked for updates to download.


The checking event has been fired. If no updates are
found, the noupdate event is fired.

3 DOWNLOADING Resources are being downloaded to the cache. The


downloading event has been fired.

4 UPDATEREADY The cache has been updated with new resources, and all
resources have been downloaded. The updateready
event has been fired.

5 OBSOLETE The manifest is missing and no cache is available. The


obsolete 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

The behavior of the cache depends entirrely on updates to the man


T nifest file. Makking a change e to a
r
resource on th
he server no longer guaranntees the brow wser will get the latest versiion of the file; if a web
p
page e resource willl be loaded frrom the application cache even if there is a newer
caches a resource, the
v
version on the
e server.

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

A change to tthis comment will be ackno


owledged as a change to th
he manifest file, for example:

#versio
on=1.2.4

You can also use


Y u the updatte() function of the applicationCache o object to initiaate a check fo
or updates,
s
similar to the one performe ed when a we eb page is firstt loaded. Any existing cachhed resources will continue
t be used un
to ntil the page iss reloaded or you invoke thhe swapCache() function o of the applicaationCache
o
object.

IIn the code exxample below w, the swapCacche() function


n is called if th
he cache has b
been updated
d with new
r
resources READY status).. This code forces the web page to use the new
(status code 4 is the UPDATER
r
resources.

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.

You have decided to make parts of the w


Y web applicatio
on available offline
o by using the offline web
w
a
application fe
eatures of HTM
ML5. After an attendee has visited the on
nline website once, their brrowser will
h
have downloaaded and cachhed the important pages. Iff a Wi-Fi conn
nection is unavailable, the aattendee will
s be able to
still o view the website by using
g the cached information.

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

• Virtual Machines: 2048


80A-SEA-DEV1
11-09, MSL-TMG1
• User Nam
me: Student

• Password
d: Pa$$w0rd
9-22 Adding Offline Support to Web Applications

Exercise 1: Caching Offline Data by Using the Application Cache API


Scenario
In this exercise, you will make the Home, About, Schedule, and Location pages available offline.

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.

The main tasks for this exercise are as follows:

1. Configure the application cache manifest

2. Detect offline mode by using JavaScript code

3. Test the application

X Task 1: Configure the application cache manifest


1. Start the MSL-TMG1 virtual machine if it is not already running.
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.

3. Configure Internet Explorer to enable support for application caching.

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.

X Task 2: Detect offline mode by using JavaScript code


1. Open offline.js file in the scripts folder. This script contains methods that hide or show links,
depending on whether a page is currently running in online or offline mode. The pages that support
offline mode reference this script.

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.

X Task 3: Test the application


1. Run the application and view the index.htm page.
2. Expand the Windows notification area, right click IIS Express and then click Exit. Allow IIS Express to
exit when prompted.
Programming in HTML5 with JavaScript and CSS3 9-23

The following image shows the IIS Express icon.

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

Exercise 2: Persisting User Data by Using the Local Storage API


Scenario
Currently, the Schedule page is able to display sessions when offline, but this information does not
include whether the attendee selected the session by using the star icon. This information is stored on a
remote server that is inaccessible when the application is running offline. However, attendees also need to
see the sessions they have selected. This information should be saved locally on an attendee’s computer,
so it is available offline.
In this exercise, you will update the JavaScript code for the Schedule page to record an attendee's
selected sessions. You will create an object that wraps the Local Storage API. Then you will use this
wrapper to save locally information about starred sessions. Finally, you will run the application, view the
Schedule page, and verify that the starred sessions are persisted even when the web server is not
available.

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.

The main tasks for this exercise are as follows:

1. Observe the current behavior of the Schedule page

2. Save information about starred session to local storage


3. Load information about starred session from local storage

4. Use the local storage wrapper to save and load data in the Schedule page

5. Test the application

X Task 1: Observe the current behavior of the Schedule page


1. In Visual Studio, open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.

2. Run the application and view the schedule.htm 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.

X Task 2: Save information about starred session to local storage


1. In the scripts folder, open the LocalStarStorage.js file. The code in this file wraps the Local Storage
API to provide a higher-level interface used by the application code.

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.

2. Implement the LocalStarStorage save method.

• 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 3: Load information about starred session from local storage


1. In the LocalStarStorage.js file, implement the LocalStarStorage load method.

• Get the stars item from local storage.

• Parse the JSON string into an array and assign it to this.sessions.


• Handle the cases when the local storage returns no data or invalid JSON. In these situations, set
this.sessions to be an empty array.

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:

// TODO: Check if item is starred

3. Add JavaScript code after this comment to:

• 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);).

4. In the unsetStar method, find the following comment:

// TODO: remove the star from the item

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:

// TODO: add a star to the item

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.

X Task 5: Test the application


1. Open the appcache.manifest file and insert a version comment near the top of the file:

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.

2. Run the application and view the schedule.htm page.

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.

6. Verify that the same sessions are still starred.


7. Close Internet Explorer.

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.

You have also


Y o learned howw to use the appplication cacche of HTML5 to configure web pages an
nd to enable
t
them to cachee resources lo
ocally on the user's
u device.

Questionn: What are th he primary diffferences betw


ween data reta
ained on a user's device byy
using sesssion storage aand by using local storage??

V
Verify the correctness of th
he statement b
by placing a m
mark in the co
olumn to the rright.

Statement Answer

You configu ure a web pag ge to use the application


a caache to cache a resource
locally. If the resource is modified at th
he web serverr, then the bro
owser
automatically downloadss the latest version. True orr false?
 
10-1

Module 10
Implementing an Adaptive User Interface
Contents:
Module Overview 10-2 

Lesson 1: Supporting Multiple Form Factors 10-3 

Lesson 2: Creating an Adaptive User Interface 10-9 


Lab: Implementing an Adaptive User Interface 10-19 

Module Review and Takeaways 10-27 


10-2 Implementing an Adaptive User Interface

Modu
ule Ove
erview

Onne of the most enduring feaatures of the web is its tem


mporary nature e. For the firstt time, the mo
onopoly of
thee keyboard annd mouse is coming under challenge, an nd that meanss questioning how user inte erfaces are
de
esigned. You may
m develop a web application on a com mputer with a large, high-re esolution mon nitor, a
mo ouse, and a keeyboard, but oother users m
might view andd interact with
h your applica ation on a smaartphone or
a ttablet withoutt a mouse, or have a monitor with a diffe
erent resolutio
on. They may also want use ers to print
pages of your application.

In this module, yyou will learn how to buildd a website tha


at adapts the layout and fu unctionality off its pages
to the capabilities and form ffactor of the d
device on which it is being viewed. You w will see how to detect
thee type of deviice being used n strategies for laying out content that effectively
d to view a paage, and learn
tarrgets particulaar devices.

Ob
bjectives
Aftter completing this module
e, you will be able to:

• Describe the requiremen


nts in a websitte for respond
ding to differe
ent form facto
ors.

• Create webb pages that ca


an adapt their layout to ma
atch the form factor of the device on wh
hich they
ed.
are displaye
Programming in HTTML5 with JavaScrippt and CSS3 10-3
3

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?

At the heart of every


e websitee is the conten nt that it displays. The desig
gn of a websitte should pressent this
content to make e it easy to usse and navigatte. However, while
w many developers com mmonly desig gn websites
forr use on a dessktop or a laptop with a scrreen resolutio on typically exceeding 1280 0 x 1024 pixelss, with a
moouse and keyb board for inpu ut, users visiting these sitess may access tthem by using g a smartphon ne or tablet,
or they may wissh to print outt pages for latter reference o offline. Conse
equently, it is becoming
b inccreasingly
ne
ecessary to dessign websites for devices withw capabilitie es that are unknown when the applicatio on is built.
These capabilitiees include the e screen resolu ution, device orientation, innput method (mouse, finge er, voice,
keyyboard, pen), and so on.

The developer'ss ability to sele


ect the contennt displayed on
o a website m might be limitted; it is typicaally driven
byy commercial decisions
d baseed on the requirements of the organizattion for which h the website is
constructed. Ho owever, as a developer, you u can make de esign choices that enhance a website so that it
ressponds intellig
gently to the fform factor of the user's de
evice. By fine--tuning the layyout of a web bsite to the
ewport of the browser, increasing the tarrget area on links for smalle
vie er screens and
d touch-based d devices,
and removing u unnecessary navigation aidss and heading gs when printiing out a page, you can op ptimize the
reaading experience for the de evice. The adaaptive user intterface features of HTML5 and CSS, such h as media
quueries and connditional comm ments, enable e you to desiggn and implem ment a websitte that reacts iin this
maanner.

Note: Thee adaptive useer interface features of HTM


ML5 and CSS3 3 enable developers to design
pplications thaat follow the responsive web design approach. The terrm responsive
ap e web design
waas coined in 20010 by Ethan Marcotte. For more inform mation, visit
htttp://go.microssoft.com/fwlin
nk/?LinkID=26 67739.

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.

Onne common d dilemma is whether to build d a second site e specifically for


f users of a certain device
e type.
Maany organizattions build shaadow website es for smartphones or otherr mobile devicces, and use fe eatures of
the
e browser to ddetect the devvice capabilitiies and redirect the user to the mobile vversion of a we
eb page, if
ne
ecessary. This approach
a requires a nontrivvial amount ofo initial effortt and design b
based on build
ding two
Programming in HTML5 with JavaScript and CSS3 10-5

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

Moost issues con


ncerning how to build an ad nterface for a website are rreally considerations
daptive user in
ab
bout the aspeccts and capabilities of the d
devices that a website should target and to which it sh hould react.
The following se marize these isssues, and desccribe some acctions that can
ections summ n be taken to enhance
the
e user experie
ence of your websites
w for differing device
e capabilities.

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.

Note: Mo ng HTML5 by Using CSS3", described maany of these techniques in


odule 6, "Stylin
de
etail.

• 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.

Note: You u can use the JavaScript exppression docuument.docum mentElementt.offsetHeigh ht


to determine thhe height of th
he viewport foor the current document, and the expresssion
do
ocument.docu umentElementt.offsetWidth to determine the width. Yo ou can also usse media querries
to detect the resolution of th
he display devvice. This approach is described in the ne
ext lesson.

• Layout. Thee most commmon response tto viewport siize is to chang


ge the layout of the website,
switching to
o a one-colum
mn layout for low viewport sizes and to high-column
h layouts for much larger
Programming in HTML5 with JavaScript and CSS3 10-7

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.

Note: You can examine the window.navigator.userAgent property in JavaScript to detect


information about the current browser displaying a web page.

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.

• Links and Abbreviations: Expand links and abbreviations on the page.

• 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

how to use CSSS to detect different types of devices an


IIn this lesson, you will see h nd to impleme ent a user
i
interface that can adapt to the form facttor and capab device on whiich your application is
bilities of the d
r
running.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Use mediia types to tarrget different types of devicce, and to app


ply appropriatte style sheet rules.

• Use mediia queries to identify certain properties o


of a device, an
nd to apply ap
ppropriate styyle sheet
rules.

• Identify the version of Internet Explo


orer being use
ed to view a w
web page, and
d to apply app
propriate
style shee
et rules.
• Create a sstyle sheet suitable for prin
nting the conttent displayed
d by a web page.
10-10 Implem
menting an Adaptivve User Interface

CS
SS Media Types

Deevelopers havee had some ability to tailorr styles to type


es of devices, since HTML4 identified a list of media
de
escriptors with
h which you co
ould qualify yyour style shee ets by using th
he media attrribute of the <
<link>
ele
ement. HTML4 4 recognized the following media types::
• aural: Spee
ech synthesize
ers.

• braille: Braille tactile feedback screen readers.

• handheld: Mobile device es (described as "small scre


een, monochro
ome, bitmapp
ped graphics, limited
bandwidth"" in the HTMLL4 specification, dated 19999!).

• print: Print preview scree


ens and printe
er output.

• projection:: Projectors.
• tty: Teletyp
pes.

• tv: Televisio
ons and otherr low-resolutio
on devices witth limited abillity to scroll.

• all: Applicable for all devvices.


Maany websites ccontinue to use these attrib butes today, e
especially wheen it comes to
o attaching a pprint style
eet to a page. For example
she e, the two elem ments shown in the following example link first to a sttyle sheet
containing ruless for any devicce (primarily sscreens) and tthen to a seco
ond style shee
et only for prin
nters, to
op
ptimize the content for paged media.

<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:

@media print, projection {


header, footer { display: none; }
...
}

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.

• A set of parrentheses con


ntaining the qu
uery, which co
omprises a de eristic, a colon, and then
evice characte
a target value.
The following exxamples show w how to definne a media quuery in an HTM
ML <link> ele ement and in a CSS rule.
If tthe device vie
ewing the corrresponding paage matches the
t query criteria, it will apply the CSS sttyles
asssociated with the query:

<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

• orientation: Whether the device is in portrait or landscape mode.

• resolution: The pixel density (in dpi or as a ratio) of the target device.
• aspect-ratio: The width to height ratio of the viewport.

• device-aspect-ratio: The width-to-height ratio of the device screen (or paper).

• color: The bits per color of the target display.

• color-index: The total number of colors the target device screen can show.

• monochrome: The bits per pixel in a monochrome frame buffer.

• scan: The scanning method of a TV. Possible values are progressive and interlace.

• grid: The display type of the output device: grid or bitmap.

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.

Implementing a Mobile-First Approach with Media Queries


/* Start with mobile styles - max width assumed at 480px*/
article {
column-count: 1;
line-height: 1.6;
font-size: 12px;
width: 98%;
}
@media (max-width: 600px) {
.article {
font-size: 14px;
width: 90%;
}
}
@media (max-width: 800px) {
.article {
column-count : 2;
line-height: 1.5;
width: 70%;
}
}
/*note min-width here, not max-width*/
@media (min-width: 1200px) {
.article {
column-count : 3;
width: 60%;
font-size: 16px;
line-height : 1.7;
}
}

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

Additional Reading: For more information about media queries, visit


http://go.microsoft.com/fwlink/?LinkID=267743.
P
Programming in HTM
ML5 with JavaScript and CSS3 10-15
5

Detecting
D g the Versiion of Inte
ernet Explorer by Using
U Conditional
C
Comment ts

One of the maain issues in d


O developing a w
website front end over the past few yearrs has been th he widely
v
varying levels of support foor CSS, most notably
n in the different edittions of Intern
net Explorer. FFor example,
I
Internet Explo
orer 6 incorrecctly implemennts the basic box
b model, wh hile Internet EExplorer 8 andd earlier
v
versions ignorre all of the ne
ew elements in HTML5.
To enable you
T u to build web b applicationss that can run in different vversions of Inteernet Explorer, Microsoft
h implemen
has nted conditio onal commen nts. These commments enable you to add rules to a style sheet to
t
target specificc versions of Internet Explo
orer. A conditio
onal commen nt is written ass an ordinary HTML
c
comment (so that it is igno
ored by other vendors’ brow wsers), but witth a condition nal expressionn enclosed in
s
square brackeets followed b by a section off HTML marku up, and a closing endif com mment. The co onditional
e
expression can detect the vversion of Inteernet Explorerr by using thee IE operand together with a version
n
number. For eexample, the ffollowing code detects whe ether the userr is running In nternet Explorer 10 :

<!--[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]-->

You can also use


Y u operatorss such as lt (less than), gt (ggreater than), lte (less than or equal), and
d gte
(
(greater than or equal) to d
detect a range e following exxample, which detects
e of values, ass shown in the
w
whether the user
u is running
g a version of Internet Explorer prior to version
v 10:

<!--[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 8, it also loads ie8.css.

• If the browser is Internet Explorer 7, 6, or older, it also loads ie7.css.


• If the browser is Internet Explorer 9 or 10, it also loads ie9.css.

• If the browser is Internet Explorer for Windows Phone 7, it also loads winPhone7.css.

• Finally, if the browser is not Internet Explorer, it also loads otherBrowsers.css.


It is also possible to define inline conditional comments so that all styles can be contained in a style sheet:

<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->


<!--[if IE 7 ]> <html class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)|(IE Mobile7)]><!--> <html> <!--<![endif]-->

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]-->

Additional Reading: For more information about conditional comments in Internet


Explorer, visit http://go.microsoft.com/fwlink/?LinkID=267744.
P
Programming in HTM
ML5 with JavaScript and CSS3 10-17
7

D
Defining S
Style Shee
ets for Printing

Print-specific styles enable your website content to be


P e printed corrrectly for easyy reading, with
hout spurious
s
screen artifactts such as navvigation and side menus takking up space
e on the printe ed page. You can use the
p
print media type to identiffy the appropriate styles to use. You can create these styles in a sep parate style
s
sheet, or you can use the @ @media rule tto add them inline in an exxisting style shheet, as shownn in the
f
following examples.

<link rel="stylesh
r eet" type="t
text/css" hr
ref="print.css" media="p
print" />
@media print {
.. pr
rint styling rules go heere ..
}

T styles for a printer ofte


The en implement the following
g rules:

• Remove tthe page head


der, footer, naavigation men
nus, background colors, CSSS graphics, traansforms, and
d
animation
ns.

header, footer, nav {


display : none;
}
article
e {
backg
ground : none;
}
.highlight {
trans
sform : none;
}

• Set the sizze of your fon


nts to values in points as yo
ou would for a Word docum
ment, set their color to
dark greyy, and remove e any effects such text-shaddow.

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:

• when printing a web page.


Create styyle sheets that apply only w

• 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

• Virtual Machines: 2048


80A-SEA-DEV1
11-10, MSL-TMG1

• User Nam
me: Student
• Password
d: Pa$$w0rd
10-20 Implementing an Adaptive User Interface

Exercise 1: Creating a Print-Friendly Style Sheet


Scenario
In this exercise, you will add a style sheet for formatting web pages in a style suitable for printing. You will
ensure that this style sheet is used only when a page is being printed.

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.

The main tasks for this exercise are as follows:

1. Review the Existing Application

2. Create a Style Sheet for Printing Web Pages

3. Link the Print Style Sheet to the About Page

4. Test the Application

X Task 1: Review the Existing Application


1. Start the MSL-TMG1 virtual machine if it is not already running.

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.

4. Run the application and view the about.htm page.


5. In Internet Explorer, on the Tools menu, point to Print, and then click Print Preview. Notice that the
print preview attempts to display the page header and that the text columns are too narrow.
Programming in HTML5 with JavaScript and CSS3 10-21

The Print Preview version of the About page looks like this:

FIGURE 10.1: THE ABOUT PAGE IN PRINT PREVIEW MODE


6. Close the Print Preview window and then close Internet Explorer.

X Task 2: Create a Style Sheet for Printing Web Pages


1. In the ContosoConf project, add a new style sheet named print.css to the styles folder.

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.

2. Refresh the page to ensu


ure that the m
most recent ve
ersion of the A
About page iss loaded.

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.

The Print Prreview version ut page should look like this:


n of the Abou

4. Close the Print


P Preview window and then close Intternet Explore
er.
Programming in HTML5 with JavaScript and CSS3 10-23

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

Exercise 2: Adapting Page Layout to Fit Different Form Factors


Scenario
In this exercise, you will create a style sheet that enables the pages in the Contoso Conference website to
adapt to different device form factors.

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.

The main tasks for this exercise are as follows:

1. Simulate the Web Application Running on a Small Device

2. Implement Styles for Hand-Held Devices and Smartphones

3. Test the Application

X Task 1: Simulate the Web Application Running on a Small Device


1. In Visual Studio, open the ContosoConf solution in the E:\Labfiles\Starter\Exercise 2 folder.

2. Run the application and view the index.htm page.

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

X Task 2: Implement Styles for Hand-Held Devices and Smartphones


1. Open the mobile.css style sheet in the styles folder. This style sheet is referenced in the <head>
element of the pages in the website. This style sheet is currently empty, but you will use it to specify
the styles for hand-held devices and smartphones.

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.

X Task 3: Test the Application


1. Run the application and view the Home page.

2. Use the F12 Developer Tools to resize Internet Explorer to various sizes to test that the media queries
adapt the user interface correctly.

3. Close Internet Explorer.

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.

Question n: What are thhe main device characteristtics used by m


media queries to detect whe
ether
a client device is a han
nd-held tablett?

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 

Lesson 1: Creating Interactive Graphics by Using SVG 11-3 

Lesson 2: Drawing Graphics by Using the Canvas API 11-22 


Lab: Creating Advanced Graphics 11-34 

Module Review and Takeaways 11-42 


11-2 Creatingg Advanced Graphiccs

Modu
ule Ove
erview

Higgh-resolutionn, interactive graphics


g are a key part of mmost modern aapplications. Graphics
G can help to
enhance the use er's experiencce by providing a visual asp pect to the con
ntent, making
g a website mo ore
atttractive and easier to use. Interactivity en
nables the graaphical elemeents in a website to adapt aand respond
to user input or changes to th he environme ent, and is ano
other importaant element in
n retaining thee attention
of the user and their interest in the conten nt.

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:

• Use SVG to create interactive graphicaal content.


• Use the Can
nvas API to ge
enerate graph
hical content p
programmaticcally.
Programming in HTTML5 with JavaScrippt and CSS3 11-3
3

Lesson 1
Creatting Intteractiv
ve Grap
phics by
y Using
g SVG

SSVG is an XML grammar th hat has been incorporated into


i HTML. SV
VG enables yo
ou to incorporrate
i
interactive aphical content in your web pages. SVG comprises a set
gra s of elements that you ennclose in an
<svg> eleme ent, and that become
b of the Document Object Model (DOM) ffor your web p
part o page.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to:

• Describe the elements of SVG.

• Create an
n <svg> elem
ment and embed simple gra
aphical elements inside it.
• Use SVG tto draw circle
es and ellipsess.

• Use SVG tto draw comp


plex shapes.

• Apply fill styles and strrokes to SVG e


elements.
• Use gradiients and pattterns to fill SV
VG elements.

• Use SVG tto draw text.

• Apply transformations to SVG eleme


ents.
11-4 Creatingg Advanced Graphiccs

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

• Call DOM fu h as documen


unctions such nt.querySelecct() and docu ument.getElementById() tto locate
and manipuulate SVG-relaated elementss in the docum
ment in JavaSccript code.

• Apply CSS sstyles such as colors, borde


ers, and transfo
ormations to SVG-related e
elements.

• 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.

Whhen you add SSVG-related elements


e to yo
our web page
e, the perform page depends on the
mance of the p
nu
umber of elem
ments. The mo ore elements yyou add, the mmore objects tthe browser has
h to create aand add to
the
e DOM tree, aand the longeer it will take the
t browser to
o render the page.
p If you w
want to create extremely
complex graphical figures, th
he Canvas API might be a b better option.
Programming in HTTML5 with JavaScrippt and CSS3 11-5
5

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>

The <svg> element can co


T ontain any num mber of SVG--related eleme ents, such as <
<rect> or <ellipse>. Each
o these elements has a sett of propertiess that enable yyou to configure its appearance within tthe <svg>
of
e
element. The following list describes som
me of the commmon propertties that you ccan set on SVG G-related
e
elements:

• 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.

• width and height: The


e width and height of the shape.
s

• fill and sttroke: The fill color and strroke color of tthe shape.

The following example crea


T ates an <svg>> element thaat contains tw wo rectangles. The first recta
angle is red
a has round
and ded corners, aas specified byy the rx and rry attributes. The
T second re ectangle is yelllow, and
p
partially obscu
ures the first rrectangle because it is defin
ned after it in
n the <svg> eelement:

<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

SSVG defines <


<circle> and <ellipse> ele
ements that en
nable you to draw
d circles and ellipses in an <svg>
e
element.

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.

The following example crea


T ates two circle es. The first circle is red and
d the second circle
c is yellow
w. The second
d
c
circle partiallyy obscures the
e first circle be
ecause it is deefined after it in the <svg> element:

<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.

The following example crea


T ates two ellipsses. The first e
ellipse is red aand the second ellipse is yellow. The
e
ellipses have tthe same shappe because th hey have the ssame rx and ry r properties. However, the e ellipses have
e
d
different cy properties, so tthey appear aat different vertical offsets w within the <sv
vg> element:

<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..

The following exxample create


es a polyline tthat draws a ja
agged blue lin
ne:

<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.

The following exxample create


es a polygon that
t draws a yyellow block aarrow pointing
g upwards:

<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..

• L: Draw a line from the ccurrent locatio


on to a new lo
ocation.

• A: Draw an elliptical arc.


Programming in HTML5 with JavaScript and CSS3 11-9

• 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.

Additionaal Reading: FFor more inforrmation about fill rules, visiit


htttp://go.microssoft.com/fwlin
nk/?LinkID=2667747.

• stroke-dassharray: Speciifies a pattern of dashes and gaps to use


e when drawin ng the outline
e. The
dasharray attribute is a series of numbers specified
d by spaces orr commas. The e first number specifies
the length of
o a dash; thee second number specifies tthe length of a gap; the third number sp pecifies the
he next dash; the fourth number specifie
length of th es the length o
of the next gaap; and so on.. Numbers
can be exprressed either as
a absolute vaalues or as percentages.
The following exxample create
es a rectangle
e with a black interior and n
no outline:

<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

Ussing Gradients and Patterns

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>

ections describe these elem


The following se ments in more
e detail.

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

• offset: Specifies the loca olor stop along the linear g


ation of the co gradient.

• stop-color: Specifies the


e color to apply at this location along the
e linear gradie
ent.

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>

The <radialGradient> Element


The <radialGradient> element creates a radial gradient of colors that can be applied to a shape. The
<radialGradient> element has two attributes named fx and fy that define the focal point of the radial
gradient on the target shape.
You can specify any number of color stops in a radial gradient. Each color stop has offset and stop-color
attributes; the offset attribute represents a percentage distance from (fx,fy) to the edge of the outermost
circle.
The following example shows how to define a radial gradient. The radial gradient is focused on a point
30% from the top left corner of the target shape, because the fx and fy values are 0.3. There are two color
stops that are applied as concentric circles centered on (fx, fy), creating a radial gradient that ranges from
yellow to red:

<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 <pattern> Element


The <pattern> element creates a pattern that can be applied to a shape. The <pattern> element has
attributes that specify the width and height of the pattern. The content to display in the pattern is
specified as a child element of the <pattern> element.

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.

Creating Reusable Gradients and Patterns


A web page might use a particular gradient or pattern at several different places. Rather than defining
each gradient or pattern separately, you can define them once within a <defs> element, and then refer
to them by their id when you want to apply them to elements in your page.

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

SSVG provides a <text> ele


ement that enables you to d
draw graphicaal text. You sp
pecify the textt between the
<text> start tag
t and the </text>
< end tag.

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 following sections desccribe how to aapply these cu


The ustomizationss.

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:

<svg xmlns="http://www.w3.org/2000/svg" id="decoratedText">


<g fill="yellow" stroke="purple" stroke-width="2" font-size="36" font-
family="verdana" font-weight="bold">
<text x="20" y="50">Normal text</text>
<text x="20" y="150" text-decoration="line-through">Text with line
through</text>
<text x="20" y="250" text-decoration="underline">Underlined text</text>
<text x="20" y="350" text-decoration="underline line-through">
Underlined text with line through
</text>
</g>
</svg>

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:

<svg xmlns="http://www.w3.org/2000/svg" id="textPath">


<path id="wavyPath1"
fill="none" stroke="green" stroke-width="5"
d="M 50 250
C 150 150 250 50 350 150
C 450 250 550 350 650 250
C 750 150 850 150 850 150" />
<text font-size="46" fill="red" font-family="Verdana">
<textPath xlink:href="#wavyPath1">
Mae hen wlad fy nhadau yn annwyl i mi!
</textPath>
</text>
</svg>

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:

<svg xmlns="http://www.w3.org/2000/svg" id="textSpans">


<defs>
<path id="wavyPath2"
d="M 50 250
C 150 150 250 50 350 150
C 450 250 550 350 650 250
C 750 150 850 150 850 150" />
</defs>
<text font-size="46" fill="orange" font-family="Verdana" stroke="purple">
<textPath xlink:href="#wavyPath2">
<tspan>Cubic equation: 5x</tspan>
<tspan dy="-30" fill="green" font-size="33">3</tspan>
Programming in HTML5 with JavaScript and CSS3 11-17

<tspan dy="+30"> + 4x</tspan>


<tspan dy="-30" fill="green" font-size="33">2</tspan>
<tspan dy="+30"> + 6x - 5 = 0</tspan>
</textPath>
</text>
</svg>
11-18 Creating Advanced Graphhics

Trransforming SVG Ellements

Traansformationss enable you to


t relocate, re a reshape an element. Yo
esize, rotate, and ou can use
tra on with JavaSccript code to ccreate animatted graphics.
ansformationss in conjunctio

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.

Additionaal Reading: FFor more inforrmation about SVG transformations, visitt


htttp://go.microssoft.com/fwlin
nk/?LinkID=2667748.

Yoou can apply multiple


m transfformations on
n a shape by u
using nested <g>< elementss and then appplying the
tra
ansform attrib bute on each sshape. The folllowing exampple shows how w to perform multiple transformations
onn a rectangle. TThe example defines two rectangles; the e first rectangle is displayedd without
ansformation, and the second rectangle is displayed w
tra with a translation, a scaling of 0.5 to makke it half
thee original size
e, and a rotatio
on of 20 degrrees about a center
c point o
of (160, 160):

<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

<rect x="0" y="0" width="200" height="200" fill="url(#checkerPattern)"


stroke="orange" stroke-width="5" />
<g transform="translate(200, 200)">
<g transform="scale(0.5)">
<g transform="rotate(20, 160, 160)">
<rect x="0" y="0" width="200" height="200"
fill="url(#checkerPattern)" stroke="orange" stroke-width="5" />
</g>
</g>
</g>
</svg>
11-20 Creating Advanced Graphhics

Demonstration: Usin
ng SVG Trransforma
ations and
d Events

In this demonstration, you wiill see how to apply transfo


ormations to SSVG elements,, animate SVG
G elements,
and handle evennts on SVG elements.

De
emonstration Steps
Traansform SVG Elements

1. ndows 8 Start screen, click the Desktop tile.


On the Win

2. On the Win
ndows taskbarr, click Interne
et Explorer.

3. In Internet Explorer, open the file E:\D


Democode\Sv
vgDocumentt.html.

4. If a message box appears asking if you


u want to allo
ow blocked co
ontent, click th
he Allow bloccked
content buutton.
5. In Internet Explorer, clickk the Transformations buttton.

6. Right-click the web page


e in Internet EExplorer, and tthen click View
w source.

7. In the sourcce window, locate the <!-- Demonstrate transformatio


ons --> comm
ment and revie
ew the
<svg> elem ment:

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

1. In Internet Explorer, clickk the Events b


button.

2. Hover the m mouse over th he red shape o


on the left sid
de of the wind
dow. Verify tha
at the shape cchanges to
a yellow fill color and a d
dotted green border.

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.

8. Right-click in the browser window, and then click View source.


9. In the source window, locate the <!-- Demonstrate events --> comment and review the <svg>
element:

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.

11. Close the source window.

12. Close Internet Explorer.


11-22 Creating Advanced Graphhics

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:

• ow the Canvass API works.


Describe ho

• Create a <ccanvas> elem


ment on a web
b page and usse the Canvas API to draw ssimple shapess and lines.

• Use the Can


nvas API to drraw complex sshapes.
• Fill shapes b
by using gradients and patterns.

• 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?

The Canvas API enables you to draw gra


T aphical shapess onto a bitma
ap area on the web page. T To use the
C
Canvas API, yo
ou add a <canvas> eleme ent to the page and then caall JavaScript ffunctions to d
draw shapes
o the canvass drawing surfface.
on
The Canvas API uses a "fire
T e-and-forget" model. When n you call Java
aScript functio
ons to draw sh
hapes on a
c
canvas, it is ass if you are pa
ainting shapess on a piece o
of paper. As so
oon as you have drawn the shapes, the
d
drawing is commplete. The shapes are nott retained in the DOM tree,, so there is no way to interract with the
s
shapes afterwwards. For exam mple, you can
nnot access shhapes by usingg the DOM, yo ou cannot apply CSS styless
t canvas shapes, and you cannot handle events on canvas shapes..
to

The performance of the Caanvas API depends on the size


T s and resolu ution of the device screen. The larger
t device, an
the nd the higher the resolutionn, the more pixels have to be
b painted an nd the slower the drawing
w be renderred. If you want to create d
will ements but that target
drawings with comprise relaatively few ele
l
large high-ressolution devicces, SVG migh
ht be a better option.
11-24 Creating Advanced Graphhics

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.

3. Invoke methods in the co


ontext object,, to draw shap
pes on the can
nvas surface.
The following exxample showss how to creatte a canvas an nd draw a rectangle upon it.i The example sets the
co
ontext.fillStyle property to o set the ambient fill color tto red for subsequent draw wing operation ns. The
exaample then caalls the conte ext.fillRect() method
m to draaw a solid recctangle. The re
ectangle will b
be filled
witth the ambiennt fill color, which is red. Th
he canvas itsellf has a dark b
blue border annd a light gre
een fill
color, due to the
e CSS style rule at the top of o the code:

<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:

• arc() and arcTo(): Draw an arc.

• quadraticCurveTo(): Draw a quadratic Bezier curve.


• bezierCurveTo(): Draw a cubic Bezier curve.

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

Yoou can draw co omplex shape


es by using a path.
p The Cannvas API has a beginPath()) function thatt enables
you to create a path connectting a series of points. You can then call functions such as moveTo o() and
lin
neTo() to movve to new locaations, and opptionally you ccan call close nnect the final point
ePath() to con
back to the firstt point.

Whhen you are ready to rende er the path, yo


ou can call the
e stroke() fun w the outline of the path.
nction to draw
Yo
ou can also call the fill() fun
nction to draww the interior of the path.

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

Ussing Gradients and Patterns

The Canvas API provides funcctions that en


nable you to specify gradien
nts and patterrns that you ccan use to
fill a shape or draw an outline
e:

• createLineaarGradient()

• createRadiaalGradient()

• createPatte
ern()

ections describe these funcctions in more


The following se e detail.

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

var canvas = document.getElementById('myCanvas');


var context = canvas.getContext('2d');
context.lineWidth = 5;
demoLinearGradient();
demoRadialGradient();
demoPattern();
function demoLinearGradient()
{
var linearGradient = context.createLinearGradient(0, 0, 0, canvas.height);
linearGradient.addColorStop(0, "red");
linearGradient.addColorStop(0.4, "yellow");
linearGradient.addColorStop(1, "green");
drawShapes(linearGradient);
}
function demoRadialGradient()
{
var radialGradient = context.createRadialGradient(canvas.width/2, canvas.height/2,
10, canvas.width/2, canvas.height/2, 100);
radialGradient.addColorStop(0, "red");
radialGradient.addColorStop(0.4, "yellow");
radialGradient.addColorStop(1, "green");
drawShapes(radialGradient);
}
function demoPattern()
{
var image = document.getElementById("wales");
var pattern = context.createPattern(image, "repeat");
drawShapes(pattern);
}
function drawShapes(theStyle)
{
// Clear any existing content in the canvas.
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw a filled triangle, using the specified style.
context.fillStyle = theStyle;
context.strokeStyle = "rgb(200, 200, 200)";
context.beginPath();
context.moveTo(70, 30);
context.lineTo(130, 140);
context.lineTo(10, 140);
context.closePath();
context.fill();
context.stroke();
// Draw a stroked circle, still using the specified style.
context.beginPath();
context.arc(canvas.width/2, canvas.height/2, 50, 0, 2*Math.PI);
context.fill();
// Draw a stroked triangle, using the specified style.
context.fillStyle = "rgb(200, 200, 200)";
context.strokeStyle = theStyle;
context.beginPath();
context.moveTo(230, 30);
context.lineTo(290, 140);
context.lineTo(170, 140);
context.closePath();
context.fill();
context.stroke();
}
</script>
11-30 Creating Advanced Graphhics

The shapes generated by thiss code look likke this:

FIGURE 11.2: SHAPES


S FILLED WIT
TH A PATTER
RN FROM AN
N IMAGE FILE
E
P
Programming in HTM
ML5 with JavaScript and CSS3 11-31
1

T
Transform
ming Shap
pes

The Canvas API enables you to transform


T m the coordin
nates of the ca
anvas context so that subse
equent
d
drawing operations are perrformed on a transformed coordinate syystem. To use transformatioons in the
C
Canvas API, use the following functions:
• rotate(an
ngle): Rotatess the coordinaate system by the specified angle clockw
wise in radianss.

• translatee(dx, dy): Tran


nslates the co
oordinate syste
em by the spe
ecified distancce in the X and Y
directionss.
• scale(sx, sy): Scales th
he coordinate system by the
e specified fra
action in the X and Y directtions.

• 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

In this demonstration, you wiill see how use


e transformattions to rotate
e, skew, and trranslate graph
hics.

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.

3. In Internet Explorer, open the file E:\D


Democode\Ca
anvasDocum
ment.html.

4. If a message box appears asking if you


u want to allo
ow blocked co
ontent, click th
he Allow bloccked
content buutton.

5. In Internet Explorer, clickk the Separate


e Transforma
ations button
n.
6. Right-click the web page
e in Internet EExplorer. and tthen click View
w source.

7. In the sourcce window, locate the dem


moSeperateTrransformatio
ons function and review the
e code:

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

Perform Matrix Transformation

1. In Internet Explorer, click the Matrix Transformations button.


2. In the source window, locate the demoMatrixTransformations function and review the code:

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.

3. Close the source window.


4. Close Internet Explorer.
11-34 Creating Advanced Graphhics

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

• Virtual Macchines: 20480A 1-11, MSL-TMG1


A-SEA-DEV11

• User Name: Student


• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 11-35

Exercise 1: Creating an Interactive Venue Map by Using SVG


Scenario
In this exercise, you will create an interactive conference venue map.

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:

1. Review the incomplete HTML markup for the venue map

2. Complete the SVG venue map


3. Add interactivity to the venue map

4. Test the application

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.

4. Open the location.htm file.

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

The venue map


m currentlyy looks like this:

FIGURE 11.2: THE INCOMPLETE VENUE


V MAP
7. Close Intern
net Explorer.

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

<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>

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.

X Task 4: Test the application


1. Run the application and view the location.htm page.

2. Move the cursor over each room and verify that the fill color changes.

The venue map should look like this:

FIGURE 11.3: THE VENUE MAP WITH ROOM A HIGHLIGHTED


3. Click each room and verify that the correct information is displayed next to the venue map.
11-38 Creating Advanced Graphhics

The informa
ation displaye
ed for Room B should look like this:

FIGURE 11.4: THE DE


ETAILS FOR R
ROOM B
4. Close Intern
net Explorer.

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

Exercise 2: Creating a Speaker Badge by Using the Canvas API


Scenario
In this exercise, you will use the Canvas API to draw the elements of a conference speaker’s badge.

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.

The main tasks for this exercise are as follows:


1. Create the canvas element

2. Draw the details for the badge

3. Test the application

X Task 1: Create the canvas element


1. In Visual Studio, open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.

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.

3. Find following comment:

<!-- TODO: Add canvas here -->

4. Add a <canvas> element, with a width of 500 and a height of 200.

5. Add a solid black border to the canvas by using a CSS style. Set the width to 1px.

6. Add the following custom attributes to the canvas element:

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.

X Task 2: Draw the details for the badge


1. Open speaker-badge.js file in the scripts\pages folder. The JavaScript code in this file contains a
refactored version of the drag-and-drop code that you created during an earlier lab exercise. Notice
that the canvas element on the page has been assigned to this.canvas. The file also contains a
number of other functions that will draw the various elements of the speaker's badge.

Note: The other drawing methods of the speaker badge page object will use the context,
assigned to this.context, to do their drawing.

2. In the drawBadge method assign this.context to be the canvas’s 2D context.


3. Use the helper methods defined in this script to perform the following tasks:
11-40 Creating Advanced Graphics

• Draw the background (use the drawBackground function).

• 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).

• Draw the speaker name (use the drawSpeakerName function).

• 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).

4. In the drawBackground method, fill the canvas with a white rectangle.

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.

The following image highlights the central square portion of a rectangle.

FIGURE 11.5: THE CENTRAL SQUARE PORTION OF A RECTANGLE


6. Implement the drawSpeakerName method. The speaker’s name is available in the
this.speakerName property.

7. Configure the following context properties of the canvas properties to style the text before drawing it.

o font: 40px sans-serif.

o fillStyle: black.

o textBaseline: top.
o textAlign: left.

o fillText: the speaker's name.

X Task 3: Test the application


1. Run the application and view the speaker-badge.htm page.

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

The speakker badge sho


ould look like this:

FIGUR
RE 11.6: THE S
SPEAKER BAD
DGE FOR MA
ARK HANSON
N
4
4. Close Inte
ernet Explorerr.

Results: Afterr completing this


R t exercise, you
y will have a Speaker Bad
dge page that enables a co
onference
s
speaker to cre
eate their bad
dge.
11-42 Creating Advanced Graphhics

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.

Test Your Know


wledge

Q
Question

W
Which of the ffollowing statements abou
ut SVG is false?

S
Select the corrrect answer.

You caan use SVG to


o draw comple
ex shapes, and
d fill them witth gradients and
patterns.

SVG elements are pparsed by the browser when


n the page is first loaded, and
a they
en discarded from memoryy.
are the

You caan create SVG


G elements dynamically by using DOM fu
unctions such as
docum
ment.createEleement().

You caan handle eve


ents on SVG elements.

SVG elements mustt be enclosed in an <svg> container


c elem
ment on a web page.

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 

Lesson 1: Applying CSS Transitions 12-3 

Lesson 2: Transforming Elements 12-11 


Lesson 3: Applying CSS Keyframe Animations 12-25 

Lab: Animating the User Interface 12-34 

Module Review and Takeaways 12-39 


12-2 Animatiing the User Interfacce

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:

• Apply transsitions to anim


mate property values to HTM
ML elements.
• Apply 2D and 3D transfo
ormations to H
HTML elements.

• Apply keyfrrame animatio


ons to HTML elements.
e
Programming in HTTML5 with JavaScrippt and CSS3 12-3
3

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;
}

CSSS transitions enable


e you to
o define a grad
dual change in property vaalues. To defin
ne a transition
n, you can
sett the CSS tran
nsition property and speciffy the followin
ng information:

• The CSS pro


operty for which you want to define a transition.

• 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
}

Additional Reading: For detailed information about CSS transitions, visit


http://go.microsoft.com/fwlink/?LinkID=267751.
12-6 Animatiing the User Interfacce

Co
onfiguring
g Transitio
ons

CSSS3 defines fivve properties tthat you can u ure a transition:


use to configu

• e CSS propertty to which the transition iss applied.


transition-property: The name of the

• transition-duration: The e length of tim


me that the trransition takess. The default value is zero seconds,
which meanns the transition happens aall at once. This has the samme effect as noot applying a transition.

• transition-timing-functtion: Specifiess how the speeed of the tran


nsition varies during its exe
ecution.
Possible vallues include "linear", "ease
e", "ease-in", "ease-out",, and "ease-inn-out". The d default
value is "ea
ase".

• transition-delay: The length of time tthat must elappse before the


e transition sttarts. The defaault value is
zero second
ds, which meaans the transittion starts imm
mediately.

• transition: Shorthand prroperty for the e other four transition prop


perties, in the order transittion-
property trransition-durration transittion-timing-ffunction tran nsition-delay y. If any of the
ese values
are not specified, the deffault values de
escribed abovve apply.

Additionaal Reading: FFor further info


ormation abo
out CSS transittions properties, see
htttp://go.microssoft.com/fwlin
nk/?LinkID=26 67751.

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.

The event argum


ment for the ttransitionend
d event-handller function has two properties:

• propertyName: The nam me of the CSSS property for which the traansition has co
ompleted, succh as width,
height, or ffont-size.

• elapsedTim me: The elapse


ed time of the elay that occurred before
e transition in seconds, excluding any de
the transitio
on started.
The following exxample showss how to hand dle the transitionend even nt on all the <
<div> elemen nts in the
do
ocument. The event-handle er function forr the transitio
onend event aadds a messag ge to a <select> drop-
do
own list, to ind
dicate the nam
me of the prop perty whose ttransition has completed an nd the elapsedd time of
the
e transition.

<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

IIn this demon


nstration, you will see how to
t apply CSS transitions
t to HTML elemen
nts. You will aalso see how
t handle the transitionen
to nd event to deetect when a ttransition has ended.

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:

o width, height, and font size


The w er a period of two seconds.
e increase ove
o The b
background ccolor transition
ns to red overr a period of 3
3.75 seconds.

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 ffirst div rule d


defines default CSS propertties for all <diiv> elements.

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 ddiv.complex ruule defines sim


milar transitio
ons, but it usess separate tran
nsition-prope
erty,
n, transition-timing-functio
transsition-duration on, and transittion-delay pro operties.

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.

2. Switch to the source window.


3. In the JavaScript code, note that:

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.

4. Close the source window.


5. Close Internet Explorer.
P
Programming in HTM
ML5 with JavaScript and CSS3 12-11
1

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:

• Describe how CSS implements transsformations.

• Apply 2D
D transformatio
ons to elemen
nts by using C
CSS.
• Apply 3D
D transformatio
ons to elemen
nts by using C
CSS.

• Apply transitions to CSSS transformattions.


12-12 Animaating the User Interfface

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.

The following co ode shows a w


web page that displays a single button. The
T transform m property in tthe styling
rulle for the buttton moves the
e button to th
he right and d
down the page e, and appliess a 45 degree skew.

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

Yoou can use the


e transform p property to pe erform one orr more transfo ormations functions on an element.
e
gin for a transfformation is tthe center of tthe target element. To chan
The default orig nge the origin
n of
tra
ansformation, set the transform-origin property and specify the fo ollowing value
es:
• Horizontal position: A len
ngth, a percen
ntage of elem
ment width, orr left, center, or right.

• Vertical possition: A lengtth, a percentage of element height, or to


op, center, orr bottom.

This topic describes how to p


perform the fo
ollowing 2D trransformation
ns:
• Translate

• 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

• tx specifies a horizontal ttranslation to the left (if ne


egative) or the
e right (if posiitive). The valu
ue can be
an absolutee length or a p
percentage off the element width.

• ty specifies a vertical tran


nslation upwa ards (if negativve) or downwwards (if positivve). The value
e can be an
absolute lenngth or a perccentage of the e element heiight. If you caall translate() and omit the e ty
parameter, the default va alue for ty is 0.
0
Programming in HTML5 with JavaScript and CSS3 12-15

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)

Note the following points about the sx and sy parameters:

• 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.

• -webkit-transform: Perform a transformation on


n Webkit-base
ed browsers ssuch as Chrom
me and Safari.
• -moz-tra
ansform: Perfform a transfo
ormation on M
Mozilla browse
ers.

• -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

1. In Internet Explorer, open the file E:\Democode\2DScaling.html.

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.

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
scaling transformations for all the <div> elements. The CSS rules set the standard transform
property, as well as vendor-specific properties.

6. Close the source window.


Perform 2D Rotations

1. In Internet Explorer, open the file E:\Democode\2DRotations.html.

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.

Perform 2D Skewing Transformations

1. In Internet Explorer, open the file E:\Democode\2DSkewing.html.


2. Verify that the browser displays a series of rectangles. Each rectangle demonstrates how to perform a
2D skewing operation by using the skew(), skewX(), or skewY() functions.

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
skewing transformations for all the <div> elements.

6. Close the source window.

7. Close Internet Explorer.


P
Programming in HTM
ML5 with JavaScript and CSS3 12-19
9

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:

• scale3d(sxx, sy, sz)

• scaleZ(sz))

The sz parameter specifies the scaling fa


T actor in the Z axis. In the sccale3d() functtion, the sy an
nd sz
p
parameters hey both default to 0.
arre optional; th

R
Rotating Ellements
T perform a 3D rotation, u
To use the follow
wing function:
• rotate3d((xnum, ynum, znum, angle))

The angle parameter speciifies the angle


T e of rotation anticlockwise
a o clockwise (if positive)
((if negative) or
a
about the dire
ection vector specified by tthe first three parameters. FFor example:
12-20 Animating the User Interface

• rotate3d(1, 0, 0, 60deg) performs a rotation about the X axis

• rotate3d(0, 1, 0, 60deg) performs a rotation about the Y axis


• rotate3d(0, 0, 1, 60deg) performs a rotation about the Z axis

Setting the Perspective and the Perspective Origin


When you specify a 3D transformation, you must also define a perspective. The perspective sets the
viewer's position relative to the object being transformed and defines how content gets smaller as the Z
value varies. If you do not specify a perspective, all points in the Z axis are flattened into the same 2D
plane without any perception of depth. There are two ways to specify perspective:
• Call the perspective() function every time you use the transform property.

• 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

The following image showss how the bro


T owser renders two <div> elements.

FIGUR
RE 12.2: REND MENTS WITH A 3D PERSP
DERING ELEM PECTIVE
12-22 Animaating the User Interfface

Defining Trransitions for Transformation


ns

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.

• Set the tran


nsition prope
erty so that it d
defines a tran
nsition for the transform CSS 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:

• #contain ner: Specifies a perspective for all the chiild elements of


o the contain
ner element, aand a
transition
n of five secon
nds for transfo
ormations.
• #contain
ner:hover: Spe e user hovers over the container
ecifies a rotation of 90 degrees when the
element.

• #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.

11. Close Internet Explorer.


P
Programming in HTM
ML5 with JavaScript and CSS3 12-25
5

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.

• Start keyfframe animatiions programmatically.

• Handle th
he events thatt occur during
g a keyframe animation.
a
12-26 Animaating the User Interfface

Defining a Keyframe
e Animatio
on

CSSS enables youu to define ke


eyframe animaations for elemment propertyy values of HT TML elements. You can
de
efine a series of
o rule-sets that specify the property valuues at distinctt stages of the
e animation. Keyframe
K
animations enab ble you to implement soph histicated userr interface effe
ects that would previously have
req
quired video or
o third-partyy plugins.

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

Aftter you have defined


d a keyyframe animattion, the next step is to connfigure the animation prope erties. You
muust specify wh
hen the anima ation is applied and how long it lasts. Op
ptionally, you can also speccify a delay
be
efore the animmation starts, a repeat count, and whethe er the animatiion should revverse itself up
pon
completion.

Too configure a kkeyframe animmation, define


e a CSS rule thhat applies the
e keyframe an nimation to an n element
in the documen nt. Inside the C
CSS rule, you ccan set the fo
ollowing propeerties to confiigure the keyfframe
animation:

• 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

In most scenarioos, you will staart keyframe animations


a prrogrammatica ally in responsse to an eventt. For
exaample, if you want the anim mation to starrt as soon as tthe web page has loaded, yyou can use th he load
eveent of the <b
body> elemen nt to trigger the animation.. If you want tto enable users to start the animation
the
emselves, provide a button n and handle tthe click even nt.

The following exxample handlles the click e event on a buttton. When th


he user clicks the
t button, thhe
sta
artAnimation n() function adds the anim mate class to th
he ball eleme es the #ball.animate
ent. This cause
CSSS rule to applly, which trigg
gers the ballm
movement ke eyframe animaation:

<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.

You can use these events to


Y o sequence an nimations. For example, yo
ou can use the
e animationend event to
t
trigger anothe
er animation on a differentt element.

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.

T following example sho


The ows how to haandle the keyfframe animatiion events forr an element n
named ball:

<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

1. ndows 8 Start screen, click the Desktop tile.


On the Win
2. On the Win
ndows taskbarr, click Interne
et Explorer.

3. In Internet Explorer, open the file E:\D


Democode\Ke
eyframeAnim
mations.htmll.

4. If a message box appears asking if you


u want to allo
ow blocked co
ontent, click th
he Allow bloccked
content buutton.

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 As the animation pro oceeds, the baall appears to


o bounce off the sides of the pool table aand the
color o
of the ball varies from white hen to orange, then to red, and then finaally to
e to yellow, th
purple..

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

7. Right-click in the browser window, and then click View source.

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: Specifies the initial appearance of the pool table.

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 @-ms-keyframes ballmovement: Defines a keyframe animation named ballmovement. The


first rule-set specifies the original color and location of the ball. Each subsequent rule-set
simulates the ball hitting one of the sides of the pool table, and causes the ball to change color
during each part of its journey. The final rule-set specifies the final color and location 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 MSAnimationIteration event-handler function is called when each iteration of the


animation has completed. The function displays a message to indicate the elapsed time of the
animation.

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.

11. Close the source window.

12. Close Internet Explorer.


12-34 Animaating the User Interfface

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.

The Feedback p page containss a form that e


enables an atttendee to pro
ovide their asssessment of th
he
conference and to make additional comments. This info ormation is suubmitted by th he Feedback page to a
data-collection service. You hhave decided that you can make this pag ge more interresting by anim
mating the
staars as the userr moves the mouse
m over them, and by mmaking the feeedback form ffly away when n the user
subbmits their feedback.

Ob
bjectives
Aftter completing this lab, you
u will be able to:
• TML elementss by using CSSS transitions.
Animate HT

• Animate HT TML elementss using CSS ke


eyframes, and trigger animaations and handle animatio
on events
by using JavvaScript code
e.

Esttimated Time:: 60 minutes

• Virtual Macchines: 20480A


A-SEA-DEV11
1-12, MSL-TMG1

• User Name: Student

• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 12-35

Exercise 1: Applying CSS Transitions


Scenario
In this exercise, you will use CSS transitions to animate parts of the conference website.

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:

1. Review the Feedback page

2. Animate the stars on the Feedback form


3. Animate the Register link on the Home page

4. Test the application

X Task 1: Review the Feedback page


1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-12 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, 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.

5. Run the application and view the Feedback page.

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.

7. Close Internet Explorer.

X Task 2: Animate the stars on the Feedback form


1. In the styles\pages folder, open the feedback.css style sheet.

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.

X Task 3: Animate the Register link on the Home page


1. The index.htm page has large Register link in the header. This link is styled by using the rules in the
header.css style sheet. In this style sheet, add CSS properties to animate the Register link when the
cursor hovers over it, as follows:
12-36 Animating the User Interface

• Rotate the link to 16 degrees and scale it by a factor of 1.1 in both dimensions.

• Transition the transformations over a period of one second.


• When the mouse moves away, return the Register link to its original state over a period of one
second.

X Task 4: Test the application


1. Run the application and view the Feedback page.
2. Move the mouse over the stars. Verify that their size changes and they remain larger when selected.

3. View the Home page.

4. Move the mouse over the Register Free link in the header and verify that it rotates and enlarges.

5. Close Internet Explorer.

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

Exercise 2: Applying Keyframe Animations


Scenario
In this exercise, you will create a keyframe animation to animate the form on the Feedback page. The
form will fly off the page when the user submits the form.

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.

The main tasks for this exercise are as follows:


1. Define a keyframe animation

2. Trigger the animation

3. Test the application

X Task 1: Define a keyframe animation


1. In Visual Studio, open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.

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.

X Task 2: Trigger the animation


1. Open the feedback.js file in the scripts\pages folder.

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.

X Task 3: Test the application


1. Run the application and view the Feedback page.

2. Click Send Feedback.


12-38 Animating the User Interface

3. Verify that the form shrinks and flies off the top of the page.

4. Close Internet Explorer.

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.

Question n: What happe


ens if you do not set the trransition-durration properrty of a CSS
transition
n?

T
Test Your Kno
owledge

Question

Which of the following operations


o can you NOT perform by using a CSS
transformattion?

Select the correct answerr.

Rotaate

Tran
nslate

Anim
mate
12-40 Animating the User Interface

Question

Scale

Skew

Question: What are the steps for implementing a keyframe animation?


13-1

Module 13
Implementing Real-time Communication by Using Web
Sockets
Contents:
Module Overview 13-2 

Lesson 1: Introduction to Web Sockets 13-3 


Lesson 2: Using the WebSocket API 13-7 

Lab: Performing Real-time Communication by Using Web Sockets 13-15 

Module Review and Takeaways 13-22 


13-2 Implementing Real-time Coommunication by Using Web Sockets

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

• ow using web sockets helpss to enable real-time comm


Describe ho munications between a web
b page and
a web serve
er.

• 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

SSockets are a long-established communication mechaanism for estaablishing a bi--directional ne etwork


c
connection etween two applications. The socket pro
be otocol enabless a server to listen for connection
r
requests at an
n advertised oor well-known address. Whe en a client connects to this address, a ne egotiation
o
occurs and the two parties establish a prrivate commu unications channel over a se eparate conne ection,
l
leaving the se
erver free to listen for further requests fro
om other clients. The clientt application aand server
e
exchange messsages over thheir private chhannel, and w
when the convversation comp pletes, either party can
c
close the connnection.

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.

• onnects to a server and excchanges data by using a we


Describe how a client aapplication co eb socket.
13-4 Implementing Real-time Coommunication by Using Web Sockets

Th
he Problem of Web
b-based Re
eal-time Communi
C cations

Wh hen creating real-time


r web
b applications,, the need forr continuous ccommunicatio on between th he web
page in a browsser and the we eb server is pa
aramount. As soon as a use er views a web b page, the daata it
dissplays might aalready be obsolete; stock values
v may haave fallen or risen,
r or the ticckets for a concert may
have sold out. A great deal of data is time dependent. U Users must be e able to trust the informatiion on the
page in front off them withouut having to reefresh it consttantly.

There are two established waays to implement real-time communicatiions:

• 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:

• Requests arre sent over HTTP.


H This mea
ans a lot of he
eader informaation is added
d to both requuest and
response, w
which in turn p
produces unwwelcome delayys in transmisssion when ope erating in real time.

• HTTP can o only send data


a one way at a time. This is known as 'half-duplex' tran
nsmission. Reaal-time
communicaation implies tthat both clien
nt and server can send andd receive messsages at the saame time,
or "full-dup
plex" transmisssion.
Programming in HTTML5 with JavaScrippt and CSS3 13-5
5

W
What is a Web Sock
ket?

Web sockets provide


W p a simple, lightweig or enabling full-duplex, real-time commu
ght method fo unications
b
between a clie elying on HTTP. Browser vendors implem
ent and a servver without re ment web sockkets
a
according to ttwo specificattion documen nts:
• RFC6455
5, which define
es the transpo
ort mechanism
m for sending and receivingg messages wwith the
minimum
m amount of aadditional info
ormation need
ded to identifyy sender and recipient.

• 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.

All four steps are carried ou


A ut transparenttly by the bro
owser in respo
onse to metho
ods implemented by the
W Sockets A
Web API.
13-6 Implementing Real-time Communication by Using Web Sockets

Additional Reading: You can read RFC6455 at


http://go.microsoft.com/fwlink/?LinkID=267756 and the latest copy of the WebSockets API at
http://go.microsoft.com/fwlink/?LinkID=267755.
Programming in HTTML5 with JavaScrippt and CSS3 13-7
7

Lesson 2
Using
g the W
WebSoccket AP
PI

This lesson inttroduces the WebSocket


T W es how you can use the WebSocket API tto implement
API. It describe
t client-side
the e logic for a p
page that opens and closes connections tto a WebSockket server, and
d uses these
c
connections to exchange m messages with
h the server.

L
Lesson Ob
bjectives
A
After completting this lesson, you will be able to write JavaScript co
ode in a web p
page that:

• Connectss to and disconnects from a web server by


b using a web
b socket.

• 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');

The default portt for the ws:/// protocol is pport 80 (like h


http). If the server is listenin
ng for connecttion
req
quests on a diifferent port, ssimply specifyy the port as p
part of the UR RL. For example:

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 initial handshake over HT TTP is perform


med automatically, and if th
he server acce
epts the reque
est from the
clie
ent a new connnection will b
be established
d by using the
e web socket transport
t prottocol.
Programming in HTML5 with JavaScript and CSS3 13-9

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.

You can bind to this event by using the onopen callback.

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

After you havve established a connection


A n to a server th
hrough a web b socket, you ccan send a me
essage to the
s
server by usin
ng the send() function of th
he WebSocke et object, like this:

var mes
ssage = ...; // Message to be sent
socket.send(message);

When the sen


W nd() function is called, the message data
a is placed in a buffer and ttransmitted
a
asynchronous
sly.

Note: TThe bufferedA Amount prop perty of the W


WebSocket ob bject reports tthe number off
bytes of data queued for se
b ending that th hat have yet to be sent. It iss set to zero w
when a
c
connection is opened. It is not reset to zzero when thee connection is closed. Befo ore sending a
m
message, you may want to check the value in the buffferedAmoun nt property to o see if any
p
previous messsages are still being sent, and delay send ding the messsage if the pre evious one has not
y been com
yet mpleted.

I an error occcurs during se


If ending, the errror event occcurs.

M
Message dataa can be sent as
a one of fourr object typess:

• e64-encoded,, and so on. The following e


Any type of UTF8 text data; plain texxt, JSON, base example uses
the JSON
N.stringify() ffunction to serialize an obje
ect as text and
d to send it:

functio
on sendRequest(socket, t
text) {
sock
ket.send(JSON.stringify(
({ request : text }));
}

• Blobs, succh as files or images. The exxample below


w sends a file specified
s by a field in an HT
TML5 form:

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:

function sendCanvasImage(socket, canvas) {


var image = canvas.getImageData(0,0,50,50);
var binArray = new Uint8Array(image.data.length);
for (var i=0; i<image.data.length; i++) {
binArray[i] = image.data[i];
}
socket.send(binArray);
}

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:

• type, whiich indicates w


whether the tyype of messag
ge received iss text or binaryy data.

• data, whiich contains the message d


data.
T following code shows aan example:
The

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);
}
};

There are no headers on th


T he message, so
o it is assumed that you will know how tto deal with both
b text and
b
binary messagges. For example, a text me
essage may be e JSON that n
needs parsing::

functio
on handleTextMessage(tex
xt) {
var message
m = JSON.parse(tex
xt);
if (m
message.request) { // do
o something }
}

Alternatively, it may be a binary


A b message. If so, the message
m will be
e an instance of either a blo ob or an
A
ArrayBuffer. You can speccify how binarry messages sh hould be pressented to your application by the
b
browser by seetting the binaaryType propperty of the WWebSocket ob bject; it is the responsibilityy of the
b
browser to format the data a according to
o the value specified in the binaryType property befo ore raising the
e
m
message event. The binaryyType properrty is set to bllob when a co onnection is fiirst opened, b but you can
c
change it to a
arrayBuffer iff your code exxpects to rece
eive data in this format.

The following code example shows how to handle diffferent types o


T of binary data
a. If the binary yType
p
property is set to arrayBufffer, the data is assumed to
o be an array of
o integer datta. If it is set to
o blob, then
t message iis assumed to contain imag
the ge data for a ccanvas:
13-14 Implementing Real-time Communication by Using Web Sockets

function handleBinaryMessage(binaryType, data) {


if (binaryType == "arrayBuffer") {
var binArray = new Uint8Array(data);
...
} else {
var canvas = document.getElementById("serverCanvas");
var image = canvas.getImageData(0,0,50,50);
for (int i=8; i<image.data.length; i++) {
image.data[i] = binArray[i];
}
canvas.putImageData(image.data,0,0);
...
}
}
P
Programming in HTM
ML5 with JavaScript and CSS3 13-15
5

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.

On the websitte, all questions must be displayed in reaal-time withou


O ut reloading tthe page, so that all
a
attendees and
d the speaker can see whatt has been askked. To suppo ort this require
ement, a web socket serverr
h been creaated. You need
has d to update th
he web appliccation to send
d the details o
of questions to
o the socket
s
server, and alsso to receive and
a display questions subm mitted by othe er attendees.

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.

Conference organizers are concerned ab


C bout people aasking inapproopriate questions. Therefore, a back-end
d
m
moderation syystem is also being
b developped. Conferennce attendeess should be abble to report a question
t
that they think is inappropriate. Adminisstrators can thhen mark this question for removal. The web socket
s
server will trannsmit a messaage to all connected clientss, and the web
b page must bbe updated to o remove the
q
question.

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

• User Name: Student

• Password: Pa$$w0rd
Programming in HTML5 with JavaScript and CSS3 13-17

Exercise 1: Receiving Messages from a Web Socket


Scenario
In this exercise, you will review the new Live page and JavaScript. You will write JavaScript that creates a
web socket and connect the socket to the server. Then you will handle messages received from the web
socket. You will parse the JSON serialized messages into objects that contain new questions to display on
the page. Finally, you will run the application, view the Live page and verify that it displays the questions
sent by the socket server.
The main tasks for this exercise are as follows:

1. Review the Live page

2. Receive messages by using a web socket

3. Display questions received as messages

4. Test the application

X Task 1: Review the Live page


1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-13 virtual machine 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. 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

The Live paage should loo


ok like this:

FIGURE 13.1: THE LIV


VE PAGE
5. Close Intern
net Explorer and return to Visual
V Studio.

6. In the ConttosoConf proj


oject, open the
e live.htm file
e.

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

e socket is stored in the Liv


Note: The ds of LivePage
vePage objectt as this.socket, so method
can use it.

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

X Task 3: Display questions received as messages


1. The handleSocketMessage method receives incoming messages from the web socket. The message
data is stored in the event parameter, but it is serialized as a JSON string. In this method, add
JavaScript code to perform the following tasks:

• Parse the JSON message into a JavaScript object named message.

• 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.

3. In the handleQuestionsMessage method, display each question by using the displayQuestion


method.

X Task 4: Test the application


1. Run the application and view the Live page. The server-side web socket will send a series of test
questions.
2. Verify that the following four questions appear on the page over a period of a few seconds.

• 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!!

• How much of CSS3 can I use right now?

3. Close Internet Explorer.

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

Exercise 2: Sending Messages to a Web Socket


Scenario
In this exercise, you will create a message object that contains a question to ask. You will serialize this
message and send it to the server by using the web socket. Then you will run the application, view two
concurrent instances of the Live page, and verify that asking questions results in them being displayed on
the page in both instances.

The main tasks for this exercise are as follows:


1. Format a question as a message

2. Send the message to the web socket

3. Test the application

X Task 1: Format a question as a message


1. Open the ContosoConf solution in the E:\Labfiles\Starter\Exercise 2 folder.

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 }

4. Serialize the message variable as a JSON string.

X Task 2: Send the message to the web socket


1. In the askQuestion method, send the JSON serialized message to the web socket.

X Task 3: Test the application


1. Run the application and view the Live page.

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.

5. Close Internet Explorer.

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

Exercise 3: Handling Different Web Socket Message Types


Scenario
In this exercise, you will add a link next to each question to enable a student to report the question as
inappropriate. Then you will handle messages from the server instructing the page to remove a question;
this process will involve handling different types of messages. Finally, you will run the application, view the
Live page, and verify that clicking the link causes the question to be removed.

The main tasks for this exercise are as follows:


1. Display report links

2. Send the report message

3. Handle Remove Question messages


4. Test the application

X Task 1: Display report links


1. Open the ContosoConf solution in the E:\Labfiles\Starter\Exercise 3 folder.

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.

3. Uncomment the following line of the displayQuestion method:

//item.appendChild(this.createReportLink());

• This statement adds the Report link next to each question.

X Task 2: Send the report message


1. When a Report link is clicked, the handleQuestionsClick event handler changes the text of the link
to Reported, and then calls the reportQuestion method. In the reportQuestion method, send the
socket a message with the following format (this message specifies the ID of the question being
reported):

{ report: questionId }

X Task 3: Handle Remove Question messages


1. Update the handleSocketMessage method to dispatch remove messages to the
handleRemoveMessage method. Previously, this method just handled messages containing
questions to be displayed.

X Task 4: Test the application


1. Run the application and view the Live page.

2. Verify that Report links are displayed next to questions.

3. Test that clicking a Report link removes the question (there will be a short delay while the question is
assessed).

4. Close Internet Explorer.

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

Web socket clients send an


W nd receive datta over an HTT
TP connection
n. True or
F
False?

Test Your Know


wledge

Q
Question

H
How does a cllient create a connection tto a web sock
ket server?

S
Select the corrrect answer.

The client uses the open() functio


on of the Web
bSocket objecct and specifie
es the URL
of the server.

The client uses the connect() function of the W


WebSocket ob
bject and speccifies the
URL off the server.

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.

The client creates a new WebSoccket object an


nd specifies the URL of the sserver.
Programming in HTML5 with JavaScript and CSS3 13-23

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 

Lesson 1: Understanding Web Workers 14-3 

Lesson 2: Performing Asynchronous Processing by Using Web Workers 14-9 


Lab: Creating a Web Worker Process 14-18 

Module Review and Takeaways 14-24 


14-2 Perform
ming Background Proocessing by Using W
Web Workers

Modu
ule Ove
erview

JavaScript ccode is a powerful tool for implementing g functionalityy in a web pag


ge, but you need to remem mber that
this code ru
uns either wheen a web page loads or in response to u user actions while the web p page is being displayed.
The code iss run by the browser, and iff the code perrforms operations that takee a significant time to compplete, the
browser can n become unrresponsive an nd degrade the user's experrience.
HTML5 intrroduces web w workers, which enable you to offload pro ocessing to se
eparate backg ground threadds and thus
enable the browser to reemain responssive. This mod dule describess how web wo orkers operatee and how you u can use
them in you ur web applications.

Ob
bjectives
Aftter completing this module
e, you will be able to:

• w web workers can be used


Explain how d to implemen
nt multithread
ding and imprrove the respo
onsiveness
of a web ap
pplication.
• Perform pro
ocessing by using a web wo
orker, commu
unicate with a web worker, and control a web
worker.
Programming in HTTML5 with JavaScrippt and CSS3 14-3
3

Lesson 1
Unde
erstand
ding We
eb Worrkers

Web worrkers enable you to perform m long-runnin ng tasks asyncchronously, en


nabling the brrowser to remain
responsivve. Each web w worker runs as a separate thread in its ow wn isolated environment. AAn application
n can initiate
a web woorker and com mmunicate witth it by passin ng it messagess. The application can also terminate the
e web
workers tthat it creates. In this lesson
n, you will learn how web wworkers operate and see the different typpes of web
workers tthat HTML5 provides.

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.

• Describe the different types of web workers that HTML5 suppo


orts.
14-4 Perform
ming Background Proocessing by Using W
Web Workers

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.

Note: Whhile it is a help


pful analogy too consider we
eb workers as the client-side equivalent of
o
muultithreading on a server, itt is important to note that JavaScript
J web workers are
e in fact
considerably sim
mpler than the e counterpartss, and do not feature semaphores,
eir server-side
muutexes, or thre
ead-blocking features.

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

W Use a Web Worrker?


Why

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.

• Performing lengthy calcu ulations. A we


eb worker cou
uld be used too implement a complex algoorithm that
implementss a computation-intensive ccalculation. Th
he results can
n be returned to the web pa
age when
the calculattion is comple
ete.

• 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.

Web workers are hosted in the browser, but they do not


W n have acce ess to the document of the web page
t
that creates th
hem, or to thee data and JavvaScript objeccts for that paage, outside of the confiness of its own
c
code. Web wo orkers run in a restricted en
nvironment an nd only have access to a limmited subset o of the
f
features proviided by JavaScript, such as the navigato or object, the location obje ect, and the application
c
cache. A web worker can perform
p I/O op using the File API, and can send and rece
perations by u eive requests
t remote servers by using the XMLHttp
to pRequest objject. Web worrkers can also create other web workers.

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

There are two tyypes of web w a shared workers.


worker: dedicaated workers and

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();

Note: The e self variable


e is an alias for this; it refere
ences the Wo orker object frrom code being
runn by the objecct. All web wo
orkers create tthe self alias when
w they sta
art running, an
nd it is
reccommended that
t you use it rather than this; it is posssible that the code being ruun by the webb
woorker manipulates this after the web worker has been n started, so performing thiis.close() mig
ght
ot have the expected effect.
no

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

Weeb worker scripts are comp pletely isolated


d from the we eb page, meaning that theyy have no acccess to
ob
bjects in that p
page or in the
e DOM for tha at page. Insteaad, a web pag
ge and a web worker comm municate by
passing messages to each oth her.
o send a messaage to a web worker, the w
To web page can use the postM Message() fuunction of the web
woorker object. T
This function ttakes a param
meter containing the data to o send to the web worker. This
parameter can b be a string or a JSON objecct. To receive a message, thhe web worker handles the message
eve
ent. The inforrmation sent bby the web paage is available in the data property of tthe event objeect passed
to the handler. TTo send a message back fro om a web woorker to the paage, the proce
ess is reversed
d; the web
woorker uses the
e postMessag ge() function, and the web page receivess the message e by handling the
meessage event of the web worker
w object.

The following exxample showss the code forr a simple web


b worker that echoes the data it is sent b
back to the
we
eb page:

// proces
ssScript.js
function messageHanddler(event) {
self.po
ostMessage(""Received: " + event.dat
ta);
}
self.addE
EventListeneer("message", messageHan
ndler, false
e);

The code in the web page loo


oks like this:

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 message. A human-readable error message.

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.

Hoowever, proce essing large im


mages will cau
use the web brrowser to beccome unrespoonsive while it performs
thiis processing. You thereforee decide to usse a web workker to move the image con
nversion to a b
background
proocess, enablin
ng the web brrowser to remain responsive e.

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.

• Send messaages to and re


eceive messag
ges from a web worker.

Esttimated Time:: 60 minutes


• Virtual Macchines: 20480A 1-14, MSL-TMG1
A-SEA-DEV11

• User Name: Student

• Password: Pa$$w0rd
P
Programming in HTML5 with JavaScript and CSS3 14-19

Exercise 1: Improving Responsiveness by Using a Web Worker


Scenario
In this exercise, you will move slow-running image processing code into a web worker.

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.

The main tasks for this exercise are as follows:


1. Review the Speaker Badge page

2. Convert the speaker badge image to grayscale

3. Create a web worker to perform image processing


4. Move image processing code into the web worker

5. Return image data from the web worker

6. Test the application

X Task 1: Review the Speaker Badge page


1. Start the MSL-TMG1 virtual machine if it is not already running.

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.

X Task 2: Convert the speaker badge image to grayscale


1. Open the speaker-badge.js JavaScript file in the scripts/pages folder. The JavaScript code in this
page contains the functions that enable a user to drop an image onto the canvas and draw the badge
(you added this functionality in a previous lab). Notice that the JavaScript code also contains a
reference to the grayscaleImage function in a variable, also called grayscaleImage.

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

3. Run the application and view the speaker-badge.htm page.

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:

1. Right-click the Windows Taskbar and then click Task Manager.


2. In Task Manager, click More details, and then click the Performance tab.

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.

3. Close Internet Explorer.

X Task 3: Create a web worker to perform image processing


1. In the grayscale.js file in the grayscaleImage function, create a web worker that runs the code in the
/scripts/grayscale-worker.js JavaScript file.

• 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

X Task 4: Move image processing code into the web worker


1. Move the grayscalePixel function from grayscale.js to grayscale-worker.js
2. Move the pixels variable and for loop that performs the conversion to grayscale from the
grayscaleImage function in grayscale.js into the message callback function of grayscale-worker.js.

• 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

X Task 5: Return image data from the web worker


1. In the grayscale-worker.js file, in the message callback, return the updated image data by posting a
message with the following format:

{ 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:

// Update the canvas with the gray scaled image data.


context.clearRect(0, 0, canvas.width, canvas.height);
context.putImageData(imageData, 0, 0);
// Returning a jQuery Deferred makes this function easy to chain together with other
deferred operations.
// The canvas object is returned as this can be used like an image.
deferred.resolveWith(this, [canvas]);

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.

X Task 6: Test the application


1. Run the application and view the Speaker Badge page.

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.

2. Drag and drop the file E:\Labfiles\Resources\mark-hanson-large.jpg onto the canvas.


3. Verify that the page is still responsive while the image is being processed.

4. Close Internet Explorer.

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

Exercise 2: Providing User Feedback for a Long Running Process


Scenario
In this exercise, you will display and update a progress bar to indicate the progress being made by the
image processing code running in the web worker.

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.

The main tasks for this exercise are as follows:


1. Add a progress bar to the Speaker Badge page

2. Send progress messages from the web worker

3. Receive progress messages from the web worker


4. Test the application

X Task 1: Add a progress bar to the Speaker Badge page


1. In Visual Studio, open the ContosoConf.sln solution in the E:\Labfiles\Starter\Exercise 2 folder.

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

Note: Use a <progress> element to display a progress bar.

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.

Note: progress is a jQuery function that generates progress notifications.

X Task 2: Send progress messages from the web worker


1. Open the grayscale-worker.js file in the scripts folder. After the grayscalePixel function, add the
following variable and 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

The progress bar should indicate ho


ow the image processing is progressing.

FIGUR
RE 14.1: PROG
GRESS BAR FO
OR THE SPEA
AKER BADGE
E PAGE

Results: Afterr completing this


R t exercise, you
y will have modified the Speaker Bad
dge page to display
d a
p
progress bar wwhile an imag
ge is being pro
ocessed.
14-24 Perforrming Background PProcessing by Using Web Workers

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.

There are two fo


orms of web w
worker:
• A dedicatedd web worker can only be rreferenced byy the page thaat created it, and
a its lifetime
e is tied to
that of the w
web page.

• 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.

Microsoft will keep your an


M nswers to this survey private
e and confide
ential and will use your resp
ponses to
i
improve your future learnin
ng experience e. Your open aand honest fe
eedback is valuuable and apppreciated.
 
L1-11

Module 1: Overrview of HTML a


and CSS
Lab: Explor
E ing th
he Con
ntoso Confe
erence
e
A
Appliccation
n
E
Exercise 1
1: Explorin
ng the Con
ntoso Con
nference A
Applicatio
on
X Task 1: Start
S the we
eb applicatiion and view
w the Home
e page
1
1. Start the MSL-TMG1 vvirtual machin
ne if it is not aalready runnin
ng.

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.

T Home paage is displaye


The ed in Internet Explorer, like this:

RE 1.1: THE HOME PAGE


FIGUR
9
9. Scroll to tthe bottom off the Home p
page.
L1-2 Programm
ming in HTML5 withh JavaScript and CSSS3

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.

X Task 2: View the Abo


out and Schedule page
es
1. On the men
nu bar, click A
About.

2. Verify that tthe About pa


age appears, aand that the style of the Ab
bout item in tthe menu bar changes to
indicate thaat the About page has bee
en selected.
The About page looks like th
his:

FIGURE 1.2: THE ABO


OUT PAGE
3. On the men
nu bar, click S
Schedule.
4. Verify that tthe Schedule
e page appearrs.

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.

T Register page looks likke this:


The
L1-4 Programm
ming in HTML5 withh JavaScript and CSSS3

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.

4. In the First name field, ttype Eric.

5. In the Last name field, tyype Gruber.

6. my data, and then click Re


In the Emaiil address field, type dumm egister.

7. Verify that tthe message You


Y must enter a valid em
mail address appears belo
ow the Email address
a
field.

8. In the Email address field


d, type gruberre@contoso.ccom.

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..

11. In the Choo


ose a password field, type abc1234.
a
12. In the Conffirm your passsword field, type wxyz9999, and then click Register.

13. Verify that tthe message Your


Y passworrds don't matcch. Please type
e the same paassword again
n appears
below the CConfirm your password field.

4. In the Conffirm your passsword field, type abc1234


14 4, and then cllick Register.

15. Verify that tthe Thanks fo


or registering
g confirmatio
on page appeaars.

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.

T Location page looks liike this:


The

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

5. Verify that yyour distance from the con


nference venu
ue is displayed
d.

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.

2. Verify that tthe Live page


e appears.
The Live page lo
ooks like this::

FIGURE 1.7: THE LIVE


E PAGE
3. In the Ask a question boxx, type What is the best wa
ay to learn HT
TML5? and the
en click Ask.

4. Verify that tthe question aappears in the


e list below th
he box.

5. Click Reporrt adjacent to


o the new que
estion.

6. Verify that tthe question d


disappears.

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 By the seccond question


10. n, click the fiftth star and ve
erify that all fivve stars are hiighlighted.
1 By the rem
11. maining two questions
q click the fourth sstar and verifyy that four stars are highlighted.

1 In the Any additional ccomments boxx, type Good conference, aand then click Send Feedbaack.
12.

1 Verify thaat the form flie


13. es off the top
p of the page.
1 Close Inte
14. ernet Explorerr.

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

Exercise 2: Examining and Modifying the Contoso Conference Application


X Task 1: Explore the web pages for the application by using Visual Studio 2012
1. In Visual Studio 2012, in Solution Explorer, expand the ContosoConf project.

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.

7. Verify that the <head> section contains the following links:

<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>

8. Near the end of the file, find the <script> elements.

9. Verify that the following scripts are referenced:

<script src="/scripts/offline.js" type="text/javascript"></script>


<script src="/scripts/_namespace.js" type="text/javascript"></script>
<script src="/scripts/datetime.js" type="text/javascript"></script>
<script src="/scripts/pages/video.js" type="text/javascript"></script>

10. In Solution Explorer, double-click about.htm.


11. In the about.htm file, at the start of the <body> section, find the <nav> section.
L1-9

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>

15. In Solution Explorer, double-click schedule.htm.

16. In the schedule.htm file, find the <section class="page-section schedule"> element.

17. Verify that this element contains the following HTML markup:

<section class="page-section schedule">


<div class="container">
<h1>Schedule</h1>
<ul id="schedule"></ul>
</div>
</section>

18. Verify that the schedule.htm file contains the <script src="/scripts/pages/schedule.js"
type="text/javascript"> element near the end.

19. In Solution Explorer, double-click register.htm.

20. In the register.htm file, find the <section class="page-section register"> element.

21. Verify that this element contains the following HTML markup:

<section class="page-section register">


<div class="container">
<h1>Register for the conference</h1>
<form method="post" action="/registration/new" id="registration-form">
<div class="field">
<label for="first-name">First name:</label>
<input type="text" id="first-name" name="FirstName" required="required"
autofocus="autofocus"/>
</div>
<div class="field">
<label for="last-name">Last name:</label>
<input type="text" id="last-name" name="LastName" required="required"/>
</div>
<div class="field">
<label for="email-address">Email address:</label>
<input type="email" id="email-address" name="EmailAddress"
required="required"/>
</div>
<div class="field">
L1-10 Programming in HTML5 with JavaScript and CSS3

<label for="password">Choose a password:</label>


<input type="password" id="password" name="Password" required="required"
pattern="[a-zA-Z0-9]{5,}" title="At least 5 letters and numbers"/>
</div>
<div class="field">
<label for="confirm-password">Confirm your password:</label>
<input type="password" id="confirm-password" name="ConfirmPassword"
required="required"/>
</div>
<div class="field">
<label for="website">Website/blog:</label>
<input type="url" id="website" name="WebsiteUrl" placeholder="http://"/>
</div>
<div>
<button type="submit">Register</button>
</div>
</form>
</div>
</section>

22. In Solution Explorer, double-click location.htm.

23. Verify that the location.htm file contains the <script src="/scripts/pages/location.js"
type="text/javascript"> element near the end.

24. Find the <section class="travel"> element.

25. Verify that this element contains the following HTML markup:

<section class="travel">
<h1>Travelling to ContosoConf</h1>
<h2 id="distance"></h2>
...
</section>

26. Find the <section class="venue"> element.

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>

28. In Solution Explorer, double-click live.htm.


L1-11

29. Find the <section class="page-section live"> element.

30. Verify that this section contains the following HTML markup:

<section class="page-section live">


<div class="container">
<h1>Attending the conference right now? Get involved!</h1>
<form action="#">
<label for="ask-question-text">Ask a question</label>
<input id="ask-question-text" type="text" />
<button type="submit">Ask</button>
</form>
<ul>
<!-- Questions will be displayed here when received by the web socket. -->
</ul>
</div>
</section>

31. Verify that the live.htm file contains the following <script> element near the end:

<script src="/scripts/pages/live.js" type="text/javascript">

32. In Solution Explorer, double-click feedback.htm.

33. Find the <section class="page-section feedback"> element.


34. Verify that this section contains the following HTML form:

<form method="post" action="/send-feedback">


<div class="field feedback-question">
<label>How would you rate the speaker's knowledge of the topic?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field feedback-question">
<label>How well could you hear the speaker?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field feedback-question">
<label>How useful did you find the information in this talk?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field feedback-question">
<label>How would you rate the overall session?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field comments">
<label>Any additional comments?</label>
<textarea name="comments" cols="30" rows="5"></textarea>
</div>
<div class="field actions">
<button type="submit">Send Feedback</button>
</div>
</form>

35. Verify that the feedback.htm file contains the following <script> elements near the end:

<script src="/scripts/StarRatingView.js" type="text/javascript">


<script src="/scripts/pages/feedback.js" type="text/javascript">

X Task 2: Explore the structure of the project


1. In Solution Explorer, expand the images folder and verify that it contains the following folders and
files.

The images folder should contain these folders and files:


L1-12 Program
mming in HTML5 with JavaScript and CSSS3

FIGURE 1.9: FILES IN THE IMAGES


S FOLDER
2. Expand the scripts folde
er.

erify that this ffolder contain


Ve ns the followin
ng folders and
d files:

FIGURE 1.10: FILES IN


N THE SCRIPT
TS FOLDER
3. Expand the styles folderr.

erify that this ffolder contain


Ve ns the followin
ng folders and
d files:
L1-133

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">&#183; Free &#183;</
/span>

5
5. Change the word Free
e to Now, as shown
s below iin bold:

<span
n class="fre
ee">&#183; Now &#183;</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.

12. Close Internet Explorer.

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

Module 2: Creating and Styling HTML Pages


Lab: Creating and Styling HTML5 Pages
Exercise 1: Creating HTML5 Pages
X Task 1: Create a new ASP.NET web application
1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480A-SEA-DEV11-02 virtual machine if it is not already running.


3. Log on to the 20480A-SEA-DEV11-02 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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.

7. In the middle pane, click ASP.NET Empty Web Application.

8. In the Name box, type ContosoConf.

9. In the Location box, type E:\Labfiles\Starter\Exercise 1, and then click OK.

X Task 2: Add the Home page


1. In Visual Studio, on the Project menu, click Add New Item.

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

The web keeps evolving. There's a wealth of new technologies to keep up


with! ContosoConf is an in-depth exploration of HTML5, CSS3 and JavaScript, in the
heart of Seattle, WA.
</p>
<p>
Don't miss the best speakers in the business, talking about the future of
the web.
</p>
</section>

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>
&#169; 2012 Contoso
</p>
</footer>

Note: Be sure to replace the © symbol with the value &#169;

13. Close Notepad.

X Task 3: Add images to the Home Page


1. On the Windows Taskbar, click File Explorer.
L2-3

2. In Internet Explorer, browse to the E:\Labfiles\Starter\Exercise 1\Resources folder.

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:

<img src="/images/speakers/melissa-kerr.jpg" alt="Melissa Kerr"/>


Melissa Kerr

5. Replace the text David Alexander with the following HTML markup:

<img src="/images/speakers/david-alexander.jpg" alt="David Alexander"/>


David Alexander

6. Replace the text Mark Hanson with the following HTML markup:

<img src="/images/speakers/mark-hanson.jpg" alt="Mark Hanson"/>


Mark Hanson

7. Replace the text April Meyer with the following HTML markup:

<img src="/images/speakers/april-meyer.jpg" alt="April Meyer"/>


April Meyer

8. Replace the text Trey Research with the following HTML markup:

<img src="/images/sponsors/sponsor1.png" alt="Trey Research"/>

9. Replace the text Litware, Inc with the following HTML markup:

<img src="/images/sponsors/sponsor2.png" alt="Litware, Inc"/>

10. Replace the text Fourth Coffee with the following HTML markup:

<img src="/images/sponsors/sponsor3.png" alt="Fourth Coffee"/>

11. Replace the text Graphic Design Institute with the following HTML markup:

<img src="/images/sponsors/sponsor4.png" alt=" Graphic Design Institute "/>

12. Replace the text Southridge Video with the following HTML markup:

<img src="/images/sponsors/sponsor5.png" alt=" Southridge Video "/>

X Task 4: Add the About page


1. In Visual Studio, on the Project menu, click Add New Item.

2. In the Add New Item – ContosoConf dialog box, click HTML Page.

3. In the Name box, type about.htm.


4. Click Add.

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>
&#169; 2012 Contoso
</p>
</footer>

11. Close Notepad.

X Task 5: Add navigation links


1. In Solution Explorer, double-click index.htm.
2. 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 Solution Explorer, double-click about.htm.

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>

X Task 6: Run the web application


1. In Solution Explorer, double-click index.htm.

2. On the Debug menu, click Start Debugging.

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 Home page is displayed.

5. Click the About link.


6. Verify that the About page is displayed.

7. Click the Home link.

8. Verify that the Home page is displayed.


9. Close Internet Explorer and return to Visual Studio.
L2-6 Programming in HTML5 with JavaScript and CSS3

Results: After completing this exercise, you will have built a simple HTML5 web application with a Home
page and an About page.
L2-7

Exercise 2: Styling HTML pages


X Task 1: Create a new style sheet
1. In the Solution Explorer, click the ContosoConf project node.

2. On the Project menu, click New Folder.

3. In Solution Explorer, change the name of the folder to styles.


4. On the Project menu, click Add New Item.

5. In the Add New Item – ContosoConf dialog box, click Style Sheet.

6. In the Name box, type site.css.


7. Click Add.

8. In Solution Explorer, double-click index.htm.

9. After the title but before the </head> element, insert the following HTML markup:

<link href="/styles/site.css" rel="stylesheet" type="text/css" />

10. In Solution Explorer, double-click about.htm.

11. After the title but before the </head> element, insert the following HTML markup:

<link href="/styles/site.css" rel="stylesheet" type="text/css" />

X Task 2: Add CSS rules to style the pages


1. In the Visual Studio Solution Explorer, double-click site.css.

2. Delete all existing CSS content.

3. Insert the following CSS code:

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

margin: 1em 0 .25em 0;


}

4. In Solution Explorer, double-click index.htm.

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>

8. In Solution Explorer, double-click about.htm.

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>

X Task 3: Run the web application


1. On the Debug menu, click Start Debugging.

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.

4. Close Internet Explorer.

Results: After completing this exercise, you will have used CSS rules to style the Home and About pages.
L3-1

Module 3: Introduction to JavaScript


Lab: Displaying Data and Handling Events
by Using JavaScript.
Exercise 1: Displaying Data Programmatically
X Task 1: Review the existing code for the Schedule page
1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480A-SEA-DEV11-03 virtual machine if it is not already running.


3. Log on to the 20480-SEA-DEV11-03 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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:

<section class="page-section schedule>


<div class="container">
<h1>Schedule</h1>
<ul id="schedule"></ul>
</div>
</section>

9. Verify that the file contains the following HTML markup towards the end:

<script src="/scripts/pages/schedule.js" type="text/javascript"></script>

10. In Solution Explorer, expand the scripts folder.

11. Expand the pages sub-folder.


12. Double-click schedule.js.

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:

var list = document.getElementById("schedule");

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:

for (var i = 0; i < schedule.length; i++) {


var li = createSessionElement(schedule[i]);
list.appendChild(li);
}

X Task 5: Run the web application and view the Schedule page
1. In Solution Explorer, double-click schedule.htm

2. On the Debug menu, click Start Without Debugging.

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 list of sessions is displayed.


5. Close Internet Explorer.

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

Exercise 2: Handling Events


X Task 1: Add checkbox HTML elements
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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. Find the line containing the following HTML markup:

<ul id="schedule"></ul>

5. Before this line, insert the following HTML markup:

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

2. In schedule.js, find the line containing the following JavaScript code:

var list = document.getElementById("schedule");

3. After this line, add the following JavaScript code:

var track1CheckBox = document.getElementById("show-track-1");


var track2CheckBox = document.getElementById("show-track-2");

X Task 3: Add click event listeners for each checkbox


1. In schedule.js, add the following JavaScript code to the end of the file:

track1CheckBox.addEventListener("click", displaySchedule, false);


track2CheckBox.addEventListener("click", displaySchedule, false);

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:

var tracks = schedule[i].tracks;


var isCurrentTrack = (track1CheckBox.checked && tracks.indexOf(1) >= 0) ||
(track2CheckBox.checked && tracks.indexOf(2) >= 0);
if (isCurrentTrack) {
var li = createSessionElement(schedule[i]);
list.appendChild(li);
}

X Task 5: Run the web application and view the Schedule page
1. In Solution Explorer, double-click schedule.htm.

2. On the Debug menu, click Start Without Debugging.


L3-4 Programming in HTML5 with JavaScript and CSS3

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.

6. Clear Track 1 and verify that no sessions appear.


7. Close Internet Explorer.

Results: After completing this exercise, you will have updated the Schedule page to filter sessions based
on which tracks have been selected.
L4-1

Module 4: Creating Forms to Collect and Validate User Input


Lab: Creating a Form and Validating User
Input
Exercise 1: Creating a Form and Validating User Input by Using HTML5
Attributes
X Task 1: Modify the Register Page
1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480A-SEA-DEV11-04 virtual machine if it is not already running.

3. Log on to the 20480A-SEA-DEV11-04 virtual machine as Student with the password Pa$$w0rd.

Note: If it is necessary, click Switch User to display the list of users

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 register.htm.

8. Find and review the comment that starts with the following text:

TODO: Add form inputs

9. In the <head> element, verify that the following HTML markup is present:

<link href="/styles/pages/register.css" rel="stylesheet" type="text/css" />

10. Before the </body> tag near the end of the file, verify that the following HTML markup is present:

<script src="/scripts/pages/register.js" type="text/javascript"></script>

X Task 2: Add Form Inputs to the Register Page


1. In the register.htm file, delete the following HTML markup:

<!-- Use the following template for the inputs -->


<div class="field">
<label for="{input-id}">label:</label>
<input type="{type}" id="{input-id}" name="{input-name}" />
</div>

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>

3. On the Debug menu, click Start Without Debugging.


4. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.

5. In the First name box, type Josh.


6. In the Last name box, type Bailey.

7. In the Email address box, type josh.bailey@adatum.com.

8. In the Choose a password box, type Passw0rd.


9. In the Confirm your password box, type Passw0rd.

10. In the Website/blog box, type http://adatum.com/.

11. Click Register.


12. Verify that the Thanks for registering page is displayed.

13. In the page header, click the Register link to return to the Register page.

14. Leave the fields empty, and then click Register.


15. Verify that the following messages are displayed:

Invalid registration information


The FirstName field is required.
The LastName field is required.
The EmailAddress field is required.
The Password field is required.
The ConfirmPassword field is required.

16. Close Internet Explorer.

X Task 3: Make the Form More User Friendly


1. In Visual Studio, in Solution Explorer, double-click register.htm.

2. Find the line containing the following HTML markup:

<input type="text" id="first-name" name="FirstName" />

3. Add the autofocus attribute shown below in bold to this line:

<input type="text" id="first-name" name="FirstName" autofocus="autofocus" />


L4-3

4. Find the line containing the following HTML markup:

<input type="url" id="website" name="WebsiteUrl" />

5. Add the placeholder attribute shown below in bold to this line:

<input type="url" id="website" name="WebsiteUrl" placeholder="http://" />

6. On the Debug menu, click Start Without Debugging.

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.

X Task 4: Check for Missing Mandatory Data


1. In Solution Explorer, double-click register.htm.

2. Find the line containing the following HTML markup:

<input type="text" id="first-name" name="FirstName" autofocus="autofocus" />

3. Add the required attribute shown below in bold to this line:

<input type="text" id="first-name" name="FirstName" required="required"


autofocus="autofocus" />

4. Find the line containing the following HTML markup:

<input type="text" id="last-name" name="LastName" />

5. Add the required attribute shown below in bold to this line:

<input type="text" id="last-name" name="LastName" required="required" />

6. Find the line containing the following HTML markup:

<input type="email" id="email-address" name="EmailAddress" />

7. Add the required attribute shown below in bold to this line:

<input type="email" id="email-address" name="EmailAddress" required="required" />

8. Find the line containing the following HTML markup:

<input type="password" id="password" name="Password" />

9. Add the required attribute shown below in bold to this line:

<input type="password" id="password" name="Password" required="required" />

10. Find the line containing the following HTML markup:

<input type="password" id="confirm-password" name="ConfirmPassword" />

11. Add the required attribute shown below in bold to this line:

<input type="password" id="confirm-password" name="ConfirmPassword"


required="required" />
L4-4 Programming in HTML5 with JavaScript and CSS3

12. On the Debug menu, click Start Without Debugging.

13. In Internet Explorer, click Register without entering any data.


14. Verify that each mandatory field is highlighted and that the form displays the following error
message:

This is a required field

15. In the First name box, type Josh.


16. In the Last name box, type Bailey.

17. In the Email address box, type josh.bailey@adatum.com.

18. In the Choose a password box, type Passw0rd.


19. In the Confirm your password box, type Passw0rd.

20. In the Website/blog box, type http://adatum.com/.

21. Click Register, and verify that the Thanks for registering page appears.
22. Close Internet Explorer.

X Task 5: Add Password Complexity Validation


1. In Solution Explorer, double-click register.htm.

2. Find the line containing the following HTML markup:

<input type="password" id="password" name="Password" required="required" />

3. Add the pattern and title attributes shown below in bold to this line:

<input type="password" id="password" name="Password" required="required"


pattern="[a-zA-Z0-9]{5,}" title="At least 5 letters and numbers" />

4. On the Debug menu, click Start Without Debugging.


5. In Internet Explorer, in the First name box, type Josh.

6. In the Last name box, type Bailey.

7. In the Email address box, type josh.bailey@adatum.com.


8. In the Choose a password box, type abc.

9. In the Confirm your password box, type abc.

10. Click Register.


11. Verify that the Choose a password box displays the following error message:

You must use this format: At least 5 letters and numbers

12. In the Choose a password box, type Passw0rd.

13. In the Confirm your password box, type Passw0rd.

14. In the Website/blog box, type http://adatum.com/.

15. Click Register, and verify that the Thanks for registering page appears.

16. Close Internet Explorer.


L4-5

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

Exercise 2: Validating User Input by Using JavaScript


X Task 1: Write Code to Get the Contents of the Password Input Elements
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

6. Find the following comment:

// TODO: Task 1 - Get the password <input> elements from the DOM by ID

7. After the comment, add the following JavaScript code:

var passwordInput = document.getElementById("password");


var confirmPasswordInput = document.getElementById("confirm-password");

X Task 2: Write Code to Compare the Password and Confirm-Password Inputs


1. In the register.js file, find the line containing the following comment:

// TODO: Task 2 - Compare passwordInput value to confirmPasswordInput value

2. After the comment, add the following JavaScript code:

var passwordsMatch = passwordInput.value === confirmPasswordInput.value;

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

2. After this comment, add the following JavaScript code:

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

2. After the comment, add the following JavaScript code:

passwordInput.addEventListener("input", checkPasswords, false);


confirmPasswordInput.addEventListener("input", checkPasswords, false);
L4-7

3. In Solution Explorer, double-click register.htm.

4. On the Debug menu, click Start Without Debugging.


5. In Internet Explorer, in the First name box, type Josh.

6. In the Last name box, type Bailey.

7. In the Email address box, type josh.bailey@adatum.com.

8. In the Choose a password box, type abc123.

9. In the Confirm your password box, type abc456.

10. Click Register.

11. Verify that the Confirm your password box displays the following error message:

Your passwords don't match. Please type the same password again.

12. In the Choose a password box, type Passw0rd.

13. In the Confirm your password box, type Passw0rd.


14. Click Register, and verify that the Thanks for registering page appears.

15. Close Internet Explorer.

X Task 5: Style Invalid Elements that are Not Valid


1. In Solution Explorer, in the ContosoConf project, expand the styles folder, and then expand the
pages folder.

2. Double-click register.css.

3. Find the comment that starts with the following text:

/* TODO: Task 5

4. Below the comment, add the following style:

.register form.submission-attempted input:invalid {


background-color: #f9b2b2;
outline: none;
}

5. In Solution Explorer, double-click register.htm.

6. On the Debug menu, click Start Without Debugging.


7. In Internet Explorer, click Register.

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

Module 5: Communicating with a Remote Server


Lab: Communicating with a Remote Data
Source
Exercise 1: Retrieving Data
X Task 1: Review the Schedule Page
1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480A-SEA-DEV11-05 virtual machine if it is not already running.


3. Log on to the 20480A-SEA-DEV11-05 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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:

var schedule = [];

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;
}

X Task 2: Create the downloadSchedule Function


1. In the schedule.js file, find the comment that starts with the following text:

// TODO: Create a function called downloadSchedule

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:

request.open("GET", "/schedule/list", true);


request.onreadystatechange = function () {
if (request.readyState === 4) {
var response = JSON.parse(request.responseText);
schedule = response.schedule;
displaySchedule();
}
};
request.send();

4. Add the following statement to the end of the schedule.js file:

downloadSchedule();

X Task 3: Add Error Handling to the downloadSchedule Function


1. In the schedule.js file, add the following code shown in bold to the downloadSchedule function:

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();
}

X Task 4: Test the Schedule Page


1. In Solution Explorer, double-click schedule.htm.
2. On the Debug menu, click Start Without Debugging.

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.

5. Close Internet Explorer.

6. In Visual Studio, double-click the schedule.js file.


7. In the downloadSchedule function, find the following statement:

request.open("GET", "/schedule/list", true);

8. Change the URL in this statement as shown in bold in the following code:

request.open("GET", "/schedule/list?fail", true);


L5-3

9. In Solution Explorer, double-click schedule.htm.

10. On the Debug menu, click Start Without Debugging.


11. In Internet Explorer, verify that the message Service currently unavailable appears.

12. In the Message from webpage dialog box, click OK.

13. Close Internet Explorer.

14. In Visual Studio, in Solution Explorer, double-click the schedule.js file.

15. In the downloadSchedule function, change the string /schedule/list?fail back to /schedule/list.

16. On the File menu, click Save All.

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

Exercise 2: Serializing and Transmitting Data


X Task 1: Send the Request to Indicate the Session that an Attendee has Selected
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

5. Find the following function:

function saveStar(sessionId, isStarred) {

6. After the last line of the TODO comment in the body of this function, add the following JavaScript
code:

var request = new XMLHttpRequest();


request.open("POST", "/schedule/star/" + sessionId, true);

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);

X Task 2: Handle the Web Service Response


1. In the schedule.js file, find the following line of code in the saveStar function:

request.open("POST", "/schedule/star/" + sessionId, true);

2. After this statement, add the following JavaScript code:

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.");
}
}
};
}

X Task 3: Test the Schedule Page


1. In Solution Explorer, double-click schedule.htm.

2. On the Debug menu, click Start Without Debugging.


3. In Internet Explorer, click the star next to New Technologies in Enterprise.

4. Verify that the following message alert is displayed:

This session is very popular! Be sure to arrive early to get a seat.

5. In the Message from webpage dialog box, click OK.


L5-5

6. Click the star next to Diving in at the deep end with Canvas.

7. Verify that no message alert is displayed.


8. Close Internet Explorer.

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

Exercise 3: Refactoring the Code by Using the jQuery ajax Method


X Task 1: Refactor the downloadSchedule Function
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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:

<script src="/scripts/pages/schedule.js" type="text/javascript"></script>

5. Immediately above this line, add the following HTML markup:

<script src="/scripts/jquery.min.js" type="text/javascript"></script>

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.");
}
});
}

X Task 2: Refactor the saveStar Function


1. In Solution Explorer, double-click schedule.js.
2. Replace the saveStar function with the following JavaScript code:

function saveStar(sessionId, isStarred) {


var request = $.ajax({
type: "POST",
url: "/schedule/star/" + sessionId,
data: { starred: isStarred }
});
if (isStarred) {
request.done(function(response) {
if (response.starCount > 50) {
alert("This session is very popular! Be sure to arrive early to
get a seat.");
}
});
}
}
L5-7

X Task 3: Test the Schedule Page


1. In Solution Explorer, double-click schedule.htm.

2. On the Debug menu, click Start Without Debugging.

3. In Internet Explorer, verify that the page displays a list of Conference sessions.

4. Click the star icon next to New Technologies in Enterprise.

5. Verify that the following message alert is displayed:

This session is very popular! Be sure to arrive early to get a seat.

6. In the Message from webpage dialog box, click OK.

7. Click the star icon next to Diving in at the deep end with Canvas.

8. Verify that no message alert is displayed.


9. In Visual Studio, in Solution Explorer, double-click schedule.js.

10. Find the string /schedule/list and replace with /schedule/list?fail.

11. On the File menu, click Save All.


12. Switch to Internet Explorer and click Refresh.

13. Verify that the error message Service currently unavailable is displayed.

14. In the Message from webpage dialog box, click OK.

15. Close Internet Explorer.

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

Module 6: Styling HTML5 by Using CSS3


Lab: Styling Text and Block Elements by
Using CSS3
Exercise 1: Styling the Navigation Bar
X Task 1: Review the HTML Structure
1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480A-SEA-DEV11-06 virtual machine if it is not already running.


3. Log on to the 20480A-SEA-DEV11-06 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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 index.htm.

8. Verify that the <head> element contains the following HTML markup:

<link href="/styles/nav.css" rel="stylesheet" type="text/css" />

9. Find the lines containing the following HTML markup:

<nav class="page-nav">
<div class="container">
<a href="/index.htm" class="active">Home</a>

10. On the Debug menu, click Start Without Debugging.

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.

13. Close Internet Explorer.

X Task 2: Style the Navigation Bar and Links


1. In Visual Studio, in Solution Explorer, expand the styles folder, and then double-click nav.css.
2. Find the following comment:

/* TODO: nav.page-nav */

3. After this comment, insert the following CSS:

nav.page-nav {
background-color: #1d1d1d;
line-height: 6rem;
font-size: 1.7rem;
L6-2 Programming in HTML5 with JavaScript and CSS3

4. Find the following CSS comment:

/* TODO: nav.page-nav .container */

5. After this comment, insert the following CSS:

nav.page-nav .container {
display: -ms-flexbox;
display: flexbox;
}

6. Find the following comment:

/* TODO: nav.page-nav a */

7. After the comment, insert the following CSS:

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;
}

8. Find the following comment:

/* TODO: nav.page-nav a:first-child */

9. After the comment, insert the following CSS:

nav.page-nav a:first-child {
border-left: 1px dotted #3d3d3d;
}

10. Find the following comment:

/* TODO: nav.page-nav a:hover */

11. After the comment, insert the following CSS:

nav.page-nav a:hover {
color: #e4e4e4;
background-color: black;
}

12. Find the following comment:

/* TODO: nav.page-nav .active */

13. After the comment, insert the following CSS:

nav.page-nav .active {
color: #fff;
background: -ms-linear-gradient(#c95656, #8d0606);
L6-3

background: linear-gradient(#c95656, #8d0606);


}

14. Find the following comment:

/* TODO: nav.page-nav .active:hover */

15. After the comment, insert the following CSS:

nav.page-nav .active:hover {
/* Override hover effect for active page link */
color: #fff;
}

X Task 3: Create Graphics by Using Pseudo Elements


1. Find the following comment:

/* TODO: nav.page-nav .active:before */

2. After the comment, insert the following CSS:

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: "";
}

3. Find the following comment:

/* TODO: nav.page-nav .active:after */

4. After the comment, insert the following CSS:

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: "";
}

X Task 4: Test the Navigation Bar


1. In Solution Explorer, double-click index.htm.

2. On the Debug menu, click Start Without Debugging.

3. Verify that the navigation bar looks similar to the following image:

The navigation bar should look like this:


L6-4 Programm
ming in HTML5 withh JavaScript and CSSS3

4. gation bar, clicck About.


In the navig

5. Verify that tthe About item is styled co


orrectly.

The About item in the navigaation bar shou


uld be displayyed like this:

OUT ITEM IN THE NAVIGA


FIGURE 6.2: THE ABO ATION BAR
6. Close Intern
net Explorer.

Results: After completing this exercise, you


R y will have styled
s the navvigation bar to
o match the design
m
mockup.
L6-5

Exercise 2: Styling the Register Link


X Task 1: Review the HTML and CSS
1. In Visual Studio, on the File menu, point to Open, and then click Open Project/Solution.

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 ContsoConf project and then double-click index.htm.

4. Verify that the <head> element contains the following HTML markup:

<link href="/styles/header.css" rel="stylesheet" type="text/css" />

5. Verify the <header> 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">&#183; Free &#183;</span>
</a>
</div>
</header>

6. On the Debug menu, click Start Without Debugging.

7. In Internet Explorer, verify that the Register link in the page header appears as an ordinary link and is
not styled.

8. Close Internet Explorer.

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:

/* TODO: header.page-header .register */

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);
}

2. Find the following CSS rule:

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);
}

4. Find the following CSS rule:

header.page-header .register:before {
}

5. Add the following CSS properties shown in bold to this rule:

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:

T Register link should loo


The ok like this:

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

Exercise 3: Styling the About Page


X Task 1: Review the HTML and CSS
1. In Visual Studio, on the File menu, point to Open, and then click Open Project/Solution.

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 ContsoConf project and then double-click about.htm.

4. Verify that the <head> element contains the following HTML markup:

<link href="/styles/pages/about.css" rel="stylesheet" type="text/css" />

5. Verify that the <body> element contains the following HTML markup:

<section class="page-section about">


<article class="container">
...
</article>
</section>

X Task 2: Define Text Columns


1. In Solution Explorer, expand the styles folder, then expand the pages folder, and then double-click
about.css.

2. In about.css, find the following CSS comment:

/* TODO: .about > article > section */

3. After this comment, add the following CSS:

.about > article > section {


column-count: 3;
column-gap: 5rem;
text-align: justify;
}

X Task 3: Add a Drop Cap at the Start of the Text


1. Find the following comment:

/* TODO: Add drop cap styling */

2. After this comment, add the following CSS:

.about p:first-child:first-letter {
font-size: 300%;
float: left;
margin: 0 0.5rem 0 0;
line-height: .8;
color: #aaa;
}

X Task 4: Indent Paragraphs


1. Find the following comment:

/* TODO: Indent paragraphs */

2. After this comment, add the following CSS:


L6-9

.about p {
text-indent: 3rem;
}
.about p:first-child {
/* Prevents text indenting after drop cap */
text-indent: 0;
margin-top: 0;
}

X Task 5: Style the Block Quote


1. Find the following comment:

/* TODO: Blockquote */

2. After the comment, add the following CSS:

.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;
}

X Task 6: Test the About Page


1. In Solution Explorer, double-click about.htm.

2. On the Debug menu, click Start Without Debugging.


3. In Internet Explorer, verify that the page looks similar to the following image:

The About page should look like this:


L6-10 Program
mming in HTML5 with JavaScript and CSSS3

FIGURE 6.4: THE ABO


OUT PAGE
4. Close Intern
net Explorer.

R
Results: After completing this exercise, you
y will have styled the textt on the Abou
ut page.
L7-1

Module 7: Creating Objects and Methods by Using


JavaScript
Lab: Refining Code for Maintainability and
Extensibility
Exercise 1: Object Inheritance
X Task 1: Review the Object.inherit.js JavaScript File
1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-07 virtual machine if it is not already running.

3. Log on to the 20480A-SEA-DEV11-07 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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.

9. Verify that the file contains the following JavaScript code:

var copyOwnProperties = function (from, to) {


for (var propertyName in from) {
if (from.hasOwnProperty(propertyName)) {
to[propertyName] = from[propertyName];
}
}
};
var inherit = function (additionalProperties) {
...
};

X Task 2: Implement the Inherit Function


1. In Object.inherit.js, find the following comment:

// TODO: Create a variable named `factory`, assign it a new object who's prototype
is `this`.

2. After the comment, add the following JavaScript code:

var factory = Object.create(this);

3. Find the following comment:

// TODO: Add a method called `create` to `factory`, that does the following

4. After the comment, add the following JavaScript: code:


L7-2 Programming in HTML5 with JavaScript and CSS3

factory.create = function() {

5. Find the following comment:

// TODO: return `instance`.

6. After the comment, add a blank line followed by the following JavaScript code:

};

7. Find the following comment:

// TODO: Copy properties of `additionalProperties` onto `factory' (using


copyOwnProperties).

8. After the comment, add the following JavaScript code:

copyOwnProperties(additionalProperties, factory);

9. Find the following comment:

// TODO: Return the `factory` object.

10. After the comment, add the following JavaScript code:

return factory;

11. In the inherit function, find the comment that starts with the following line:

// TODO: Define a variable named `instance`.

12. After the comment, add the following JavaScript code:

var instance = Object.create(factory);

13. Find the following comment:

// TODO: If `instance` has a function named "initialize",

14. After the comment, add the following JavaScript code:

if (typeof instance.initialize === "function") {


instance.initialize.apply(instance, arguments);
}

15. Find the following comment:

// TODO: return `instance`.

16. After the comment, add the following JavaScript code:

return instance;

17. Find the following comment:

// TODO: Add the inherit function to the built-in `Object` object.

18. After the comment, add the following of JavaScript code:


L7-3

Object.inherit = inherit;

X Task 3: Scope the JavaScript Code Inside an Immediately Invoked Function


Expression
1. In Object.inherit.js, add the following JavaScript code at the top of the file:

(function () {

2. Add the following JavaScript code at the end of the file:

} ());

X Task 4: Use Strict Mode


1. In Object.inherit.js, find the following comment:

// TODO: Strict mode

2. After the comment, add the following line (including the quotes):

"use strict";

3. On the File menu, click Save All.

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

Exercise 2: Refactoring JavaScript Code to Use Objects


X Task 1: Define the ScheduleList Factory
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

5. Find the following comment:

// TODO: Create a ScheduleList factory object using the Object.inherit helper


method.

6. After the comment, add the following JavaScript code:

var ScheduleList = Object.inherit({


initialize: function (element, localStarStorage) {
this.element = element;
this.localStarStorage = localStarStorage;
}
});

7. Find the comment that starts with the following line:

// TODO: Refactor these variables into properties of the ScheduleList object.

8. Delete the following line of JavaScript code after this comment:

var element, localStarStorage;

X Task 2: Convert Functions Into Methods of the ScheduleList Object


1. In schedule.js, find the following comment:

// TODO: Refactor these functions into methods of the ScheduleList object.

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):

var ScheduleList = Object.inherit({


initialize: function (element, localStarStorage) {
this.element = element;
this.localStarStorage = localStarStorage;
},
startDownload: function () {
var request = $.ajax({
url: "/schedule/list",
context: this
});
request.done(this.downloadDone)
.fail(this.downloadFailed);
},
downloadDone: function (responseData) {
this.addAll(responseData.schedule);
},
L7-5

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);
}
});

X Task 3: Create and Use a ScheduleList Object


1. In schedule.js, find the following JavaScript code:

// TODO: Replace the following code by creating a ScheduleList object


// and calling the startDownload method.
element = document.getElementById("schedule");
localStarStorage = LocalStarStorage.create(localStorage);
startDownload();

2. Delete this block of JavaScript code, and then replace it with the following code:

var scheduleList = ScheduleList.create(


document.getElementById("schedule"),
LocalStarStorage.create(localStorage)
);
scheduleList.startDownload();

X Task 4: Test the Application


1. In Solution Explorer, double-click schedule.htm.

2. On the Debug menu, click Start Without Debugging.


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 looks similar to the image below:


L7-6 Programm
ming in HTML5 withh JavaScript and CSSS3

The Schedu
ule page should still displayy the list of sesssions for the conference, like this:

FIGURE 7.1: THE SCH


HEDULE PAGE
E
5. Close Intern
net Explorer.

Results: After completing this exercise, you


R y will have refactored
r the
e JavaScript co
ode for the Scchedule
p
page to be mo ore maintainaable by using objects.
o
L8-1

Module 8: Creating Interactive Pages by Using HTML5 APIs


Lab: Creating Interactive Pages with HTML5
APIs
Exercise 1: Dragging and Dropping Images
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.


3. Log on to the 20480A-SEA-DEV11-08 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users

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.

8. In Solution Explorer, double-click speaker-badge.htm.

9. Verify that the HTML markup contains the following <img> element:

<img style="width: 300px; height: 300px; border: 1px solid #000"/>

10. Verify that the HTML markup contains the following <script> elements:

<script src="/scripts/jquery.min.js" type="text/javascript"></script>


<script src="/scripts/pages/speaker-badge.js" type="text/javascript"></script>

11. In Solution Explorer, expand the scripts folder and then expand the pages folder.

12. Double-click speaker-badge.js.

13. Verify that the JavaScript file contains the following line of code:

var SpeakerBadgePage = Object.inherit({

X Task 2: Add Drag-and-Drop Event Listeners


1. In speaker-badge.js, find the following comment:

// TODO: Add event listeners for element "dragover" and "drop" events.
// handle with this.handleDragOver.bind(this) and this.handleDrop.bind(this)

2. After the comment, add the following JavaScript code:

element.addEventListener("dragover", this.handleDragOver.bind(this), false);


element.addEventListener("drop", this.handleDrop.bind(this), false);
L8-2 Programming in HTML5 with JavaScript and CSS3

X Task 3: Handle the Drop Event


1. In speaker-badge.js, find the following comment:

// TODO: Get the files from the event

2. After the comment, add the following JavaScript code:

var files = event.dataTransfer.files;

3. Find the following comment:

// TODO: Read the first file in the array

4. After the comment, add the following JavaScript code:

var file = files[0];

5. Find the following comment:

// Check the file type is an image

6. After the comment, add the following JavaScript code:

if (this.isImageType(file.type)) {

7. Find the following comment:

// Use this.readFile to read the file, then display the image

8. After the comment, add the following JavaScript code:

this.readFile(file).done(this.displayImage);
} else {
alert("Please drop an image file.");
}

X Task 4: Read the Image by Using a FileReader


1. In speaker-badge.js, find the following comment:

// TODO: Create a new FileReader

2. After the comment, insert the following JavaScript code:

var reader = new FileReader();

3. Find the following comments:

// TODO: Assign a callback function for reader.onload


// TODO: In the callback use reading.resolveWith(context, [fileDataUrl]); to
return the file data URL

4. After these comment, insert the following JavaScript code:

reader.onload = function (loadEvent) {


var fileDataUrl = loadEvent.target.result;
reading.resolveWith(context, [fileDataUrl]);
};

5. Find the following comment:


L8-33

// 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.

T page should look like tthis:


The

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

Exercise 2: Incorporating Video


X Task 1: Add a Video Player to the Home Page
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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 node.

4. Double-click index.htm.

5. Find the comment that starts with the line:

<!-- TODO: Add video tag here -->

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>

X Task 2: Add Controls to the Video Player


1. In index.htm, after the </video> element, insert the following HTML markup:

<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>

2. Find the following comment and select it with the mouse:

<!--<script src="/scripts/pages/video.js" type="text/javascript"></script>-->

3. In the toolbar, click the Uncomment the selected lines button.


4. Verify that the HTML markup now looks like this:

<script src="/scripts/pages/video.js" type="text/javascript"></script>

X Task 3: Control the Video by Using JavaScript Code


1. In Solution Explorer, expand the scripts folder, and then expand the pages folder.

2. Double-click video.js.
3. Find the following comment:

// TODO: display the video controls

4. After this comment add the following JavaScript code:

controls.style.display = "block";

5. Find the comment that starts with the following lines:

// TODO: Add event listeners for:


// video loaddata

6. After the second line of comment, add the following JavaScript code:
L8-5

video.addEventListener("loadeddata", ready, false);

7. In video.js, find the following comment:

// TODO: play the video

8. After the comment, add the following JavaScript code:

video.play();
playButton.style.display = "none";
pauseButton.style.display = "";

9. Find the following comment:

// TODO: pause the video

10. After the comment add the following JavaScript code:

video.pause();
pauseButton.style.display = "none";
playButton.style.display = "";

11. Find the following comments:

// play click
// pause click

12. After the comments, add the following JavaScript code:

playButton.addEventListener("click", play, false);


pauseButton.addEventListener("click", pause, false);

X Task 4: Display the Video Elapsed Time


1. In video.js, find the following comment:

// TODO: Set time.textContent using the current video.current time.


// Use the formatTime function to convert raw seconds into HH:MM:SS format.

2. After the comment, add the following JavaScript code:

time.textContent = formatTime(video.currentTime);

3. Find the following comment:

// video timeupdate

4. After the comment, add the following JavaScript code:

video.addEventListener("timeupdate", updateTime, false);

X Task 5: Test the Video Player


1. In Solution Explorer, double-click index.htm.

2. On the Debug menu, click Start Without Debugging.

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.

8. Close Internet Explorer.

Results: After completing this exercise, you will have added a video player to the Home page.
L8-7

Exercise 3: Using the Geolocation API to Report the User's Current


Location
X Task 1: Review the HTML Markup and JavaScript Code
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.
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 node.


4. In Solution Explorer, double-click location.htm.

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.

8. Verify that the file contains the following JavaScript code:

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:

// TODO: Get current position from the geolocation API.

2. After the comment, add the following JavaScript code:

navigator.geolocation.getCurrentPosition(updateUIForPosition, error);

X Task 3: Display the Distance to the Conference Venue


1. In location.js, find the following comment:

// TODO: Calculate the distance from the conference

2. After the comment, add the following JavaScript code:

var distance = distanceFromConference(position.coords);

X Task 4: Test the Location Page


1. In Solution Explorer, double-click location.htm.

2. On the Debug menu, double-click Start Without Debugging.

3. In Internet Explorer, if the message localhost wants to track your location appears, click Allow
once.

4. In the Enable Location Service dialog box, click Yes.

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

Module 9: Adding Offline Support to Web Applications


Lab: Adding Offline Support to Web
Applications
Exercise 1: Caching Offline Data by Using the Application Cache API
X Task 1: Configure the application cache manifest
1. Start the MSL-TMG1 virtual machine if it is not already running.

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.

Note: If necessary, click Switch User to display the list of users.

3. On the Windows 8 Start screen, click the Desktop tile.

4. On the Windows taskbar, click Internet Explorer.

5. In the Internet Explorer, press F10 to display the menu bar.

6. On the Tools menu, click Internet options.

7. In the Internet Options dialog box, click Settings.

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.

10. In the Internet Options dialog box, click OK.

11. Close Internet Explorer.

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.

16. Find the following comment:

# TODO: Add index, about, schedule and location pages

17. After the comment, type the following URLs:

/index.htm
/about.htm
/location.htm
/schedule.htm

18. In Solution Explorer, double-click index.htm.


19. Add the manifest attribute to the <html> element, as shown in bold below:

<html lang="en" manifest="/appcache.manifest">


L9-2 Programming in HTML5 with JavaScript and CSS3

20. In Solution Explorer, double-click about.htm.

21. Add the manifest attribute to the <html> element, as shown in bold below:

<html lang="en" manifest="/appcache.manifest">

22. In Solution Explorer, double-click schedule.htm.

23. Add the manifest attribute to the <html> element, as shown in bold below:

<html lang="en" manifest="/appcache.manifest">

24. In Solution Explorer, double-click location.htm.


25. Add the manifest attribute to the <html> element, as shown in bold below:

<html lang="en" manifest="/appcache.manifest">

X Task 2: Detect offline mode by using JavaScript code


1. In Solution Explorer, expand the scripts folder, and then double-click offline.js.

2. Find the following comment:

// TODO: if currently offline, hide navigation links that require online

3. After this comment, add the following JavaScript code:

if (!navigator.onLine) {
hideLinksThatRequireOnline();
}

4. Find the following comment:

// TODO: add onoffline and ononline events to document.body

5. After this comment, add the following JavaScript code:

document.body.onoffline = hideLinksThatRequireOnline;
document.body.ononline = showLinks;

6. Find the following comment:

// TODO: also handle the applicationCache error event to hide links

7. After this comment, add the following JavaScript code:

applicationCache.addEventListener("error", hideLinksThatRequireOnline, false);

X Task 3: Test the application


1. In Solution Explorer, double-click index.htm.
2. On the Debug menu, click Start Without Debugging.

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 Internet Explorer displays the Home page.

5. Expand the Windows notification area, right-click IIS Express, and then click Exit.
L9-3

The following image shows the IIS Express icon.

FIGURE 9.1: THE IIS EXPRESS ICON IN THE WINDOWS NOTIFICATION AREA
6. In the Confirmation dialog box, click Yes.

7. In Internet Explorer, click Schedule.

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.

10. Click About.

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.

13. 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.
L9-4 Programming in HTML5 with JavaScript and CSS3

Exercise 2: Persisting User Data by Using the Local Storage API


X Task 1: Observe the current behavior of the Schedule page
1. In Visual Studio, on the File menu, click point to Open, and then click Project/Solution.

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 schedule.htm.

4. On the Debug menu, click Start Without Debugging.

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.

10. Close Internet Explorer.

X Task 2: Save information about starred session to local storage


1. In Solution Explorer, expand the ContosoConf project, expand the scripts folder, and then double-
click LocalStarStorage.js.

2. Find the following comments:

// TODO: convert this.sessions into a JSON string


// TODO: save this JSON string into local storage as "stars"

3. After the second comment, insert the following JavaScript code:

this.localStorage.setItem("stars", JSON.stringify(this.sessions));

X Task 3: Load information about starred session from local storage


1. In LocalStarStorage.js, find the following comment:

// TODO: get the "stars" from local storage

2. After this comment, add the following JavaScript code:

var json = this.localStorage.getItem("stars");

3. Find the following comments:

// TODO: parse the JSON string into this.sessions


// TODO: handle failures due to missing data etc

4. After the second comment, add the following JavaScript code:

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.

2. Find the following comment:

// TODO: Check if item is starred

3. After this comment, add the following JavaScript code:

if (localStarStorage.isStarred(this.id)) {
this.element.classList.add(this.starredClass);
}

4. Find the following comment:

// TODO: remove the star from the item

5. After this the comment, add the following JavaScript code:

this.localStarStorage.removeStar(this.id);

6. Find the following comment:

// TODO: add a star to the item

7. After this comment, add the following JavaScript code:

this.localStarStorage.addStar(this.id);

X Task 5: Test the application


1. In Solution Explorer, double-click appcache.manifest.

2. Find the following line:

CACHE MANIFEST

3. After the line, insert the following line:

# version 2

4. In Solution Explorer, double-click schedule.htm.

5. On the Debug menu, click Start Without Debugging.

6. In Internet Explorer, click Refresh.

7. Expand the Windows notification area, right-click IIS Express, and then click Exit.

8. In the Confirmation dialog box, click Yes.

9. In Internet Explorer, click the star icon in the Registration box, and verify that the icon is now colored
yellow.

10. Click Refresh.

11. Verify that the star icon for Registration is still colored yellow.
L9-6 Programming in HTML5 with JavaScript and CSS3

12. Close Internet Explorer.

Results: After completing this exercise, you will have updated the Schedule page to locally record
starred sessions.
L10-1

Module 10: Implementing an Adaptive User Interface


Lab: Implementing an Adaptive User
Interface
Exercise 1: Creating a Print-Friendly Style Sheet
X Task 1: Review the Existing Application
1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480A-SEA-DEV11-10 virtual machine if it is not already running.


3. Log on to the 20480A-SEA-DEV11-10 virtual machine as Student with the password Pa$$w0rd.

Note: If it is necessary, click Switch User to display the list of users.

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 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:

12. Close the Print Preview window.


13. Close Internet Explorer.

X Task 2: Create a Style Sheet for Printing Web Pages


1. In Visual Studio, in Solution Explorer, click the styles folder.

2. On the Project menu, click Add New Item.

3. In the Add New Item - ContosoConf dialog box, in the left pane, expand the Visual C# node, and
then click Web.

4. In the middle pane, click Style Sheet.


5. In the Name box, type print.css.

6. Click Add.

7. In print.css, delete the existing file contents.


L10-3

8. Add the following CSS:

nav.page-nav,
header.page-header,
footer.page-footer {
display: none;
}
.container {
padding: 0;
max-width: none;
}

9. In print.css, at the end of the file, add the following CSS:

.about > article > section {


column-count: 1;
}

X Task 3: Link the Print Style Sheet to the About Page


1. In Solution Explorer, double-click about.htm.

2. Find the following comment:

<!-- TODO: Add print.css <link> here -->

3. After the comment, add the following HTML:

<link href="/styles/print.css" media="print" rel="stylesheet" type="text/css" />

X Task 4: Test the Application


1. On the Debug menu, click Start Without Debugging.

2. In Internet Explorer, click Refresh.

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

The Print Prreview version


n of the Abou
ut page should look like this:

5. Close the Print


P Preview window.
6. Close Intern
net Explorer.

Results: After completing this exercise, you


R y will have added
a a style sheet that im
mplements a p
print-
friendly formaat for web pag
ges.
L10-5

Exercise 2: Adapting Page Layout to Fit Different Form Factors


X Task 1: Simulate the Web Application Running on a Small Device
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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 index.htm.

4. On the Debug menu, click Start Without Debugging.

5. In Internet Explorer, press F12.


6. In the ContosoConf – F12 window, on the Tools menu, point to Resize, and then click Custom.

7. In the Resize Browser dialog box, in the Width box, type 480.

8. In the Height box, type 800.


9. Click Add, click Resize, and then click Close.

10. Press F12.

11. Verify that the Home page looks similar to the following image:
L10-6 Program
mming in HTML5 with JavaScript and CSSS3

The Home page should look like this:

FIGURE 10.3: THE HO


OME PAGE
12. Close Intern
net Explorer.

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

2. Add the following CSS to the file:

@media screen and (max-width: 480px) {


}

3. Add the CSS rules shown below in bold to the file:

@media screen and (max-width: 480px) {


nav.page-nav .container {
display: -ms-flexbox;
-ms-flex-wrap: wrap;
-ms-flex-pack: center;
}
nav.page-nav .active:before,
nav.page-nav .active:after {
display: none;
}
nav.page-nav a {
border: 1px dotted #3d3d3d;
margin: .5rem;
}
}

4. Add the following CSS to the end of the file:

@media screen and (max-width: 720px) {


header.page-header {
height: auto;
}
header.page-header .register {
display: none;
}
header.page-header h1 {
font-size: 3rem;
}
}

X Task 3: Test the Application


1. In Solution Explorer, double-click index.htm.
2. On the Debug menu, click Start Without Debugging.

3. In Internet Explorer, press F12.

4. In the ContosoConf – F12 window, on the Tools menu, point to Resize, and then click 1280×1024.
5. Press F12.

6. Verify that the Home page is displayed correctly on the desktop.


L10-8 Program
mming in HTML5 with JavaScript and CSSS3

The Home page should look like this on the deskto


op:

FIGURE 10.4: THE HO


OME PAGE D
DISPLAYED ON
N THE DESKT
TOP
7. 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

Module 11: Creating Advanced Graphics


Lab: Creating Advanced Graphics
Exercise 1: Creating an Interactive Venue Map by Using SVG
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.


3. Log on to the 20480A-SEA-DEV11-11 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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 location.htm.

8. Verify that the page contains the following HTML markup:

<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 -->
<!-- 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>

9. Verify that the HTML contains the following markup:

<script src="/scripts/pages/location-venue.js" type="text/javascript"></script>

10. On the Debug menu, click Start Without Debugging.


11. Click Location.

12. If the message localhost wants to track your location appears, click Allow once.

13. In the Enable Location Services dialog box, click Yes.

14. If the message Intranet settings are turned off by default appears, click Don’t show this message
again.

15. Scroll down and view the venue map.


L11-2 Program
mming in HTML5 with JavaScript and CSSS3

The venue map


m should lo
ook like this:

FIGURE 11.1: THE INCOMPLETE VENUE


V MAP
16
6. Close Intern
net Explorer.

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:

<g id="room-b" claass="room">


<re
ect fill="#f
fff" x="200"" y="0" width="100" heig
ght="100"/>
<te
ext x="213" y="55" fontt-weight="bold" font-siz
ze="20">ROOMM B</text>
</g>

X Task 3: Ad
dd interactivity to the v
venue map
1. In Solution Explorer, dou
uble-click loca
ation.htm.

2. Find the folllowing HTMLL markup:

<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.

4. At the end of the file, add the following 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.

6. Find the following comment:

// TODO: Get the room elements in the svg element.

7. After this comment, add the following JavaScript code:

var rooms = document.querySelectorAll(".room");

8. Find the comment that starts with the following text:

// TODO: Add a click event listener for each room element.

9. After the second line of this comment, add the following JavaScript code:

for (var i = 0; i < rooms.length; i++) {


var room = rooms[i];
room.addEventListener("click", function () {
showRoomInfo(this.id);
});
}

X Task 4: Test the application


1. In Solution Explorer, double-click location.htm.

2. On the Debug menu, click Start Without Debugging.


3. In Internet Explorer, if the message localhost wants to track your physical location appears, click
Allow once.

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 venue map


m should lo
ook like this:

FIGURE 11.2: THE VE


ENUE MAP W
WITH ROOM A HIGHLIGHT
TED
6. Click Room
m B, verify thatt the room infformation is d d that it is similar to the following
displayed, and
image:

The informa
ation displaye
ed for Room B should look like this:

7. Close Intern
net Explorer.

Results: After completing this exercise, you


R y will have a venue map that displays extra informaation when
c
clicked.
L11-5

Exercise 2: Creating a Speaker Badge by Using the Canvas API


X Task 1: Create the canvas element
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

4. Find the following comment:

<!-- TODO: Add canvas here -->

5. After this comment, add the following HTML markup:

<canvas
width="500"
height="200"
style="border: 1px solid #888"
data-speaker-id="234724"
data-speaker-name="Mark Hanson">
</canvas>

X Task 2: Draw the details for the badge


1. In Solution Explorer, expand the scripts folder, expand the pages folder, and then double-click
speaker-badge.js.

2. Verify that the file contains the following JavaScript code:

this.canvas = element.querySelector("canvas");

3. Find the following comment:

// TODO: Get the canvas's (this.canvas) context and assign to this.context

4. After this comment, add the following JavaScript code:

this.context = this.canvas.getContext("2d");

5. Find the comment that starts with the following line:

// TODO: Draw the following by calling the helper methods of `this`

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);

7. Find the following comment:

// TODO: Fill the canvas with a white rectangle


L11-6 Program
mming in HTML5 with JavaScript and CSSS3

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);

9. Find the comment that starts


s with the
e following line:

// 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);

11. Find the comment that starts


s with the
e following line:

// 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.

3. On the taskkbar, click File


e Explorer and
d then browse
e to the E:\La
abfiles\Resou
urces folder.

4. Drag and drop mark-hanson.jpg from


m File Explore
er onto the sp
peaker badge in Internet Exxplorer.
5. Verify that tthe speaker b
badge looks similar to the fo
ollowing imag
ge:

The speaker badge should look like th


his:

FIGURE 11.2: THE SP GE FOR MARK HANSON


PEAKER BADG
6. Close Intern
net Explorer.

Results: After completing this exercise, you


R y will have a Speaker Bad
dge page thatt enables a co
onference
s
speaker to cre
eate their badg
ge.
L12-1

Module 12: Animating the User Interface


Lab: Animating the User Interface
Exercise 1: Applying CSS Transitions
X Task 1: Review the Feedback page
1. Start the MSL-TMG1 virtual machine if it is not already running.

2. Start the 20480A-SEA-DEV11-12 virtual machine if it is not already running.


3. Log on to the 20480A-SEA-DEV11-12 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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.

8. Verify that this page contains the following HTML markup:

<form method="post" action="/send-feedback">


<div class="field feedback-question">
<label>How would you rate the speaker's knowledge of the topic?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field feedback-question">
<label>How well could you hear the speaker?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field feedback-question">
<label>How useful did you find the information in this talk?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field feedback-question">
<label>How would you rate the overall session?</label>
<input name="question" type="range" min="1" max="5"/>
</div>
<div class="field comments">
<label>Any additional comments?</label>
<textarea name="comments" cols="30" rows="5"></textarea>
</div>
<div class="field actions">
<button type="submit">Send Feedback</button>
</div>
</form>

9. Verify that the HTML contains the following:

<link href="/styles/pages/feedback.css" rel="stylesheet" type="text/css" />

10. Verify that the HTML contains the following:

<script src="/scripts/pages/feedback.js" type="text/javascript"></script>


L12-2 Programming in HTML5 with JavaScript and CSS3

11. On the Debug menu, click Start Without Debugging.

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.

14. Close Internet Explorer.

X Task 2: Animate the stars on the Feedback form


1. In Solution Explorer, expand the styles folder, then expand the pages, and then double-click
feedback.css.

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);
}

X Task 3: Animate the Register link on the Home page


1. In Solution Explorer, in the styles folder, double-click header.css.
2. Update the following CSS rule, and add the code shown below in bold:

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;
}

X Task 4: Test the application


1. In Solution Explorer, double-click feedback.htm.

2. On the Debug menu, click Start Without Debugging.


3. In Internet Explorer, move the mouse over the third star of How would you rate the speaker's
knowledge of the topic?.

4. Verify that the first three stars animate to a larger size.


5. Click the third star, and then move the mouse away from the stars.

6. Verify that the first three stars remain a larger size.

7. Click Home.
8. Move the mouse over the Register Free link and verify that it rotates and enlarges.

9. Close Internet Explorer.

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

Exercise 2: Applying Keyframe Animations


X Task 1: Define a keyframe animation
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

4. Find the following comment:

/* TODO: Add key frame animation named "send"


At 0% scale(1)
At 50% scale(.8)
At 100% translate(0, -1000px)
*/

5. After this comment, add the following CSS code:

@keyframes send {
0% {
transform: scale(1);
}
50% {
transform: scale(.8);
}
100% {
transform: translate(0, -1000px);
}
}

6. Find the following comment:

/* TODO: Use the "send" animation


iteration-count: 1
fill-mode: forwards
*/

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;

X Task 2: Trigger the animation


1. In Solution Explorer, expand the scripts folder, expand the pages folder, and then double-click
feedback.js.

2. Find the following comment:

// TODO: Trigger the animation by adding the "sending" CSS class to the form

3. After this comment, add the following JavaScript code:

form.classList.add("sending");

4. find the following comment:


L12-5

// TODO: Add listener for the animationend event,


// calling the animationEnded function.

5. After this comment, add the following JavaScript code:

form.addEventListener("animationend", animationEnded, false);

X Task 3: Test the application


1. In Solution Explorer, double-click feedback.htm.

2. On the Debug menu, click Start Without Debugging.

3. In Internet Explorer, click Send Feedback.


4. Verify that the form shrinks and flies off the top of the page.

5. Close Internet Explorer.

Results: After completing this exercise, submitting the conference feedback form will trigger an
animation that makes the form fly off the page.
 
L13-1

Module 13: Implementing Real-time Communication by


Using Web Sockets
Lab: Performing Real-time Communication
by Using Web Sockets
Exercise 1: Receiving Messages from a Web Socket
X Task 1: Review the Live page
1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-13 virtual machine.

3. Log on to the 20480A-SEA-DEV11-13 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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. On the Debug menu, click Start Without Debugging.

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

The Live paage should loo


ok like this:

FIGURE 13.1: THE LIV


VE PAGE
12. Close Intern
net Explorer and return to Visual
V Studio.

13. In Solution Explorer, expand the ConttosoConf projject, and then


n double-clickk live.htm.

4. Verify that tthis page contains the follo


14 owing HTML m
markup:

<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>

15. Verify that tthe page conttains the follo


owing HTML markup:
m

<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

2. After this comment, add the following JavaScript code:

var socket = new WebSocket("ws://localhost:55981/live/socket.ashx");

3. Find the following comment:

// TODO: Assign a callback to handle messages from the socket.

4. After this comment, add the following JavaScript code:

this.socket.onmessage = this.handleSocketMessage.bind(this);

X Task 3: Display questions received as messages


1. In live.js, find the following comment:

// TODO: Parse the event data into message object.

2. After this comment, add the following JavaScript code:

var message = JSON.parse(event.data);

3. Find the following comment:

// TODO: Check if message has a `questions` property, before calling


handleQuestionsMessage

4. Modify the statement following this comment, as shown below in bold:

if (message.questions) {
this.handleQuestionsMessage(message);
}

5. Find the following comment:

// TODO: Display each question in the page, using the displayQuestion function.

6. After this comment, add the following JavaScript code:

if (message.questions) {
message.questions.forEach(this.displayQuestion, this);
}

X Task 4: Test the application


1. In Solution Explorer, double-click live.htm.

2. On the Debug menu, click Start Without Debugging.

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!!

• How much of CSS3 can I use right now?

5. Close Internet Explorer.


L13-4 Programming in HTML5 with JavaScript and CSS3

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

Exercise 2: Sending Messages to a Web Socket


X Task 1: Format a question as a message
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

4. Find the following comment:

// TODO: Create a message object with the format { ask: text }

5. After this comment, add the following JavaScript code:

var message = {
ask: text
};

6. Find the following comment:

// TODO: Convert the message object into a JSON string

7. After this comment, add the following JavaScript code:

var json = JSON.stringify(message);

X Task 2: Send the message to the web socket


1. In live.js, find the following comment:

// TODO: Send the message to the socket

2. After this comment, add the following JavaScript code:

this.socket.send(json);

X Task 3: Test the application


1. In Solution Explorer, double-click live.htm.

2. On the Debug menu, click Start Without Debugging.


3. In Internet Explorer, click New Tab.

4. In the Address bar, type http://localhost:55981/live.htm, and then press Enter.

5. In the Ask a question box, type This is a test.


6. Click Ask.

7. Verify that the list of questions displays This is a test.

8. Click the first Internet Explorer tab.


9. Verify that the list of questions includes This is a test.

10. Close Internet Explorer.


L13-6 Programming in HTML5 with JavaScript and CSS3

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

Exercise 3: Handling Different Web Socket Message Types


X Task 1: Display report links
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

4. In live.js, find the following comment:

//item.appendChild(this.createReportLink());

5. Replace this comment with the following JavaScript code:

item.appendChild(this.createReportLink());

X Task 2: Send the report message


1. In live.js, find the following comment:

// TODO: Send socket message { report: questionId }

2. After the comment, insert the following:

this.socket.send(JSON.stringify({ report: questionId }));

X Task 3: Handle Remove Question messages


1. In live.js, modify the JavaScript code in the handleSocketMessage method as shown below in bold:

handleSocketMessage: function (event) {


// TODO: Parse the event data into message object.
var message = JSON.parse(event.data);
if (message.questions) {
this.handleQuestionsMessage(message);
} else if (message.remove) {
this.handleRemoveMessage(message);
}
}

X Task 4: Test the application


1. In Solution Explorer, double-click live.htm.

2. On the Debug menu, click Start Without Debugging.

3. In Internet Explorer, after the page loads, wait five seconds.


4. Next to What are some good resources for getting started with HTML5?, click Report.

5. Wait for several seconds.

6. Verify that the What are some good resources for getting started with HTML5? question is removed
from the page.

7. Close Internet Explorer.


L13-8 Programming in HTML5 with JavaScript and CSS3

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

Module 14: Performing Background Processing by Using


Web Workers
Lab: Creating a Web Worker Process
Exercise 1: Improving Responsiveness by Using a Web Worker
X Task 1: Review the Speaker Badge page
1. Start the MSL-TMG1 virtual machine if it is not already running.
2. Start the 20480A-SEA-DEV11-14 virtual machine if it is not already running.

3. Log on to the 20480-SEA-DEV11-14 virtual machine as Student with the password Pa$$w0rd.

Note: If necessary, click Switch User to display the list of users.

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.

8. Verify that the page contains the following HTML markup:

<div class="busy">
<p>Creating badge. Please wait...</p>
</div>

9. Verify that the page contains the following HTML markup:

<script src="/scripts/grayscale.js" type="text/javascript"></script>

10. In Solution Explorer, expand the scripts folder, and then double-click grayscale.js.

11. Verify that the file contains the following JavaScript function:

conference.grayscaleImage = function (image) {


...
}

X Task 2: Convert the speaker badge image to grayscale


1. In Solution Explorer, expand the scripts folder, expand the pages folder, and then double-click
speaker-badge.js.

2. In speaker-badge.js, find the following comment:

// TODO: Add grayscaleImage into the processing pipeline.

3. Modify the code following this comment, as shown below in bold:

this.readFile(file)
.pipe(this.loadImage)
.pipe(grayscaleImage)
.done(this.drawBadge, this.notBusy);
L14-2 Programming in HTML5 with JavaScript and CSS3

4. In Solution Explorer, double-click speaker-badge.htm.

5. On the Debug menu, click Start Without Debugging.


6. In Internet Explorer, if the message Intranet settings are turned off by default appears, click Don’t
show this message again.

7. On the Windows taskbar, click File Explorer.


8. Browse to the folder E:\Labfiles\Resources.

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.

12. Close Internet Explorer.

X Task 3: Create a web worker to perform image processing


1. In Visual Studio, in Solution Explorer, in the scripts folder, double-click grayscale.js

2. Find the following comment:

// TODO: Create a Worker that runs /scripts/grayscale-worker.js

3. After this comment, add the following JavaScript code:

var worker = new Worker("/scripts/grayscale-worker.js");


worker.postMessage(imageData);

4. In Solution Explorer, in the scripts folder, double-click grayscale-worker.js.

5. Add the following JavaScript code to this file, after the comment at the top:

addEventListener("message", function (event) {


});

6. In Solution Explorer, double-click grayscale.js.

7. Find the following JavaScript statements:

var worker = new Worker("/scripts/grayscale-worker.js");


worker.postMessage(imageData);

8. Insert the following code shown in bold between these two statements:

var worker = new Worker("/scripts/grayscale-worker.js");


var handleMessage = function (event) {
};
worker.addEventListener("message", handleMessage.bind(this));
worker.postMessage(imageData);

X Task 4: Move image processing code into the web worker


1. In grayscale.js, cut the following code that defines the grayscalePixel function to the clipboard:

var grayscalePixel = function (pixels, index) {


/// <summary>Updates the pixel, starting at the given index, to be gray
scale.</summary>
L14-3

var brightness = 0.34 * pixels[index] + 0.5 * pixels[index + 1] + 0.16 *


pixels[index + 2];
pixels[index] = brightness; // red
pixels[index + 1] = brightness; // green
pixels[index + 2] = brightness; // blue
};

2. In grayscale-worker.js, underneath the existing code, paste the JavaScript code for the
grayscalePixel function from the clipboard.:

3. In grayscale.js, delete the following code:

var pixels = imageData.data;


// 4 array items per pixel => Red, Green, Blue, Alpha
for (var i = 0; i < pixels.length; i += 4) {
grayscalePixel(pixels, i);
}

4. In grayscale-worker.js, underneath the existing code, add following JavaScript code:

var grayscalePixel = function (pixels, index) {


/// <summary>Updates the pixel, starting at the given index, to be gray
scale.</summary>
var brightness = 0.34 * pixels[index] + 0.5 * pixels[index + 1] + 0.16 *
pixels[index + 2];
pixels[index] = brightness; // red
pixels[index + 1] = brightness; // green
pixels[index + 2] = brightness; // blue
};

5. Add the following code shown in bold to the addEventListener statement:

addEventListener("message", function (event) {


var imageData = event.data;
var pixels = imageData.data;
for (var i = 0; i < pixels.length; i += 4) {
grayscalePixel(pixels, i);
}
});

X Task 5: Return image data from the web worker


1. In grayscale-worker.js, after the for loop in the addEventListener statement, add the following
code shown in bold:

for (var i = 0; i < pixels.length; i += 4) {


grayscalePixel(pixels, i);
}
postMessage({ done: imageData });

2. In grayscale.js, delete the following code:

// Update the canvas with the gray scaled image data.


context.clearRect(0, 0, canvas.width, canvas.height);
context.putImageData(imageData, 0, 0);
// Returning a jQuery Deferred makes this function easy to chain together with
other deferred operations.
// The canvas object is returned as this can be used like an image.
deferred.resolveWith(this, [canvas]);

3. Find the following JavaScript statement:

var handleMessage = function (event) { };


L14-4 Programming in HTML5 with JavaScript and CSS3

4. Add following JavaScript code shown in bold to this statement:

var handleMessage = function (event) {


var message = event.data;
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]);
};

X Task 6: Test the application


1. On the Windows taskbar, click the Internet Explorer icon.

2. In Internet Explorer, press F12.

3. On the Cache menu, click Clear browser cache.


4. In the Clear Browser Cache message box, click Yes.

5. Press F12, and then close Internet Explorer.

6. In Visual Studio, in Solution Explorer, double-click speaker-badge.htm.


7. On the Debug menu, click Start Without Debugging.

8. On the taskbar, click File Explorer.

9. Browse to the E:\Labfiles\Resources folder.


10. Drag mark-hanson-large.jpg from File Explorer into Internet Explorer and drop it onto the canvas
with the label Drag your profile photo here.

11. Verify that you can scroll the page up and down while and image is being processed.

12. Close Internet Explorer.

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

Exercise 2: Providing User Feedback for a Long Running Process


X Task 1: Add a progress bar to the Speaker Badge page
1. In Visual Studio, on the File menu, point to Open, and then click Project/Solution.

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.

4. Find the following HTML markup:

<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.

7. In speaker-badge.js, find the following line:

this.busyElement = element.querySelector(".busy");

8. After this line, add the following JavaScript code:

this.progress = element.querySelector("progress");

9. Add the following JavaScript code shown in bold to the SpeakerBadgePage object, after the
initialize function:

var SpeakerBadgePage = Object.inherit({


initialize: function (element) {
...
},
updateProgress: function (progress) {
this.progress.value = progress;
},

10. Find the following comment:

// TODO: Add grayscaleImage into the processing pipeline.

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);

X Task 2: Send progress messages from the web worker


1. In Solution Explorer, in the scripts folder, double-click grayscale-worker.js.
2. In grayscale-worker.js, add the following JavaScript code shown in bold:
L14-6 Programming in HTML5 with JavaScript and CSS3

var grayscalePixel = function(pixels, index) {


...
};
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;
}
};
addEventListener("message", function (event) {
...
};

3. Update the message event callback function and add the following code shown in bold:

addEventListener("message", function (event) {


var imageData = event.data;
var pixels = imageData.data; // Pixels is an array of integers encoded as [
red, green, blue, alpha, red, green, blue, alpha, red, green, blue, alpha, ... ]
for (var i = 0; i < pixels.length; i += 4) {
grayscalePixel(pixels, i);
updateProgress(pixels, i);
}
postMessage({ progress: 100 });
postMessage({ done: imageData });
});

X Task 3: Receive progress messages from the web worker


1. In Solution Explorer, in the scripts folder, double-click grayscale.js.
2. In grayscale.js, replace the handleMessage event callback function in the grayscaleImage function
with the following JavaScript 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");
...
};

X Task 4: Test the application


1. On the Windows taskbar, click the Internet Explorer icon.

2. In Internet Explorer, press F12.


3. On the Cache menu, click Clear browser cache.

4. In the Clear Browser Cache message box, click Yes.


L14-77

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.

1 Verify thaat the progresss bar appearss while the im


11. mage is being processed.
p

The progress bar should indicate ho


ow the image processing is progressing.

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.

Potrebbero piacerti anche