Sie sind auf Seite 1von 190

Evelina Buiciag

HTML5 APPLICATIONS DEVELOPMENT MANUAL

Iai Romania
2016
ISBN: 978-973-0-24454-0

The use of this material is reserved only for private use. It is forbidden and
may be caught and multiplication law public use because constitutes a
violation of copyright law. Copywriting @ 2017 Evelina Buiciag,
AnySolution. All rights reserved.
Table of content
TABLE OF CONTENT
1 - INTRODUCTION TO HTML5 APPLICATION
2 - UNDERSTAND THE PLATFORM FUNDAMENTALS
3 - CREATING APPS
4 - PACKAGING AND THE RUNTIME ENVIRONMENT
5 - APPLICATION STATE
6 - TOUCH INTERFACES AND GESTURES
7 - DEBUGGING AND TESTING
8 - VALIDATING HTML5 CODE
9 - PUBLISHING AN APPLICATION
10 - HTML ESSENTIALS
11 - ORGANIZE CONTENT
12 - INPUT AND VALIDATION
13 - CSS INTRODUCTION
14 - CSS SINTAX
15 - MANAGING CONTENT
16 LAYOUTS
17 - MANAGING TEXT FLOW
18 - MANAGING THE GRAPHICAL INTERFACE
19 - BUILDING INTERACTIVE APPLICATIONS
20 - CREATING AND USING FUNCTIONS AND VARIABLES IN JAVASCRIPT
21 - JQUERY AND OTHER THIRD-PARTY LIBRARIES
22 - OBJECTS IN JAVASCRIPT
23 - DOCUMENT OBJECT MODEL (DOM)
24 - LOCATING AND ACCESSING ELEMENTS
25 - LISTENING AND RESPONDING TO EVENTS
26 - CHANGING, ADDING AND DELETING ELEMENTS
27 - CODING ANIMATIONS BY USING JAVASCRIPT
28 - WORKING WITH IMAGES, SHAPES, AND OTHER GRAPHICS
29 - TRANSMITTING DATA
30 - LOADING AND SAVING FILES
31 - RESPONDING TO THE TOUCH INTERFACE
32 - CODING ADDITIONAL HTML5 APIS
33 - ACCESSING DEVICE AND OPERATING SYSTEM RESOURCES
34 - BOOTSTRAP
35 WEATHER APPLICATION DEVELOPMENT
BILBLIOGRAFIE
1 - Introduction to HTML5 Application

Hi, my name it is AnySolution and I will be your


mentor throughout this HTML5 APPLICATIONS DEVELOPMENT
MANUAL.

HTML5 is the latest HTML standard and a family of technologies that


includes HTML, CSS, and JavaScript. Although the HTML5 standard wont
be finalized for a few years, most modern Web browsers already support
HTML5 elements. HTML5 app development for Web and mobile device
browsers is well underway.

Hyper Text Markup Language(HTML) is the language with which


the content of a website is made (paragraphs, images, text, etc.).

Cascade Style Sheet(CSS) is the language used to design a website


(colors, fonts, backgrounds, etc.).

JavaScript is a scripting language (a programming language that uses


scripts and requires no compiler) that adds interactivity to Web pages.
Although you can use HTML5, CSS3, and JavaScript to create Web pages,
you can also use the combination to develop client applications (apps) that
run-on touch-enabled devices like PCs, slates, tablets, and smartphones.
Essentially, the same technologies developers use to build Web pages are
now beginning used to build applications that run on different devices.
2 - Understand the platform fundamentals
Although HTML5 is HTML, it has been developed by the W3C to
work directly with CSS3 and JavaScript to allow developers and designers
the ability to create web applications that will also work on touch-enabled
devices and easily adapt to smaller screens. In addition, HTML5, CSS3, and
JavaScript are all considered platform-independent technologies and
therefore can run regardless of the operating system if the operating system
has a web browser.
For example, Windows 8 and Windows Phone 8 have the Internet
Explorer browser, Mac OS and iPhone have the Safari browser, Linux OS
has the Firefox browser and Android phones have the Google Chrome
browser. Each of these browsers can run HTML5, CSS3, and JavaScript.
However, browsers also have versions, so if the browser being used is the
newest version then most HTML5 and CSS3 features will be supported.

An important part of app development in the Windows environment is


the Metro style user interface (UI), which is the UI used by the latest
Microsoft Windows version: Windows 8. The Metro style UI includes
features like a clean, uncluttered look and feel, use of the full screen, large
hubs (graphical buttons), and a focus on lateral scrolling, to name a few.

The HTML5 family includes many new markup tags and technologies
like media queries, geolocation, Modernizr, and much more. These
technologies add a lot of functionality to HTML-based apps and help make
the finished product more stylish.
3 - Creating Apps
Creating an app requires several steps:
- Planning your project
- Designing the user interface (UI)
- Updating the app manifest
- Writing the code
- Building the app
- Debugging and testing the app
- Packaging the app
- Validating the app
- Deploying the app

1. Plan your project: Think about the type of app you want to create. After
you decide on the main action of your app, create an outline of the general
flow of the application from start to finish. Also, determine the type of user
interactivity you want to include, such as a touch interface, whether you need
to save data outside of the app, and whether the app should connect to other
apps or services (such as an RSS feed).
2. Design UI: When designing the user interface, determine how you want
the app to appear to users.
3. Update the app manifest: Every app requires a manifest file. The
manifest file describes properties of the app and what the app needs to run.
4. Write code: During this phase, you compose the code for your
application, which might include a combination of HTML, CSS, and
JavaScript.
5. Build the app: Using an app development tool such as Visual Studio,
convert your code and other resources into an actual application.
6. Debug and test: You must test your app thoroughly and fix any
problems that appear. If the app uses a touch interface, its highly important
to test the app on a touch device or use a touch emulator.
7. Package: Packaging an app creates a container that holds all the
various files required by the app, such as JavaScript, images, and so on.
8. Validate: Validating your app means running it through a validation
program to ensure nothing is missing.
9. Deploy: Upload your app to a marketplace such as the Windows
Store.
4 - Packaging and the Runtime
Environment
Application packaging is the process of bundling an application and
its resources into an archive format for distribution and deployment.

The App Container


When a Web app executes, it does so in a contained environment
- An app container is a separate memory space
The purpose of an app container is to prevent apps from corrupting
the operating system
Permissions are grouped into permission sets, and every assembly is
assigned a set. The .NET Framework defines some standard permission sets
such as FullTrust (implies all permissions) and Execution (permission to
access the CPU only).

Each user account is assigned a level of access (credentials). They can


be set to use Windows Authentication, database authentication, no
authentication, or custom authentication.

The Windows Runtime environment is the foundation of the


Windows 8 operating system and provides functionality to Metro-style apps.

When you launch an app, its considered to be in a runtime


environment (RTE). An RTE is where users run the app and developers test
it. In Windows, this environment is called Windows Runtime (WinRT).
The WinRT works with C#, C++, Visual Basic, and JavaScript. You
can build Metro style apps with the WinRT and Windows Library for
JavaScript APIs. An application programming interface (API) is simply a
list of instructions letting a program communicate with another program. In a
Web app, an API enables a Web browser or a Web server to communicate
with other programs. There are hundreds of APIs available for many different
uses.

The Document Object Model (DOM) is an important API to keep in


mind. The DOM is designed for HTML and Extensible Markup Language
(XML), and allows programs and scripts to update content, structure, and
styles on the fly - essentially anything in an HTML or XML file can be
modified. The DOM is neither HTML nor JavaScript, but it ties them
together.
5 - Application State
A session state is created when a user first requests access to an
application, and it ends when the session closes, such as when a user logs off.

An application state exists from the time a Web browser requests a


Web page until the browser closes. Persistent state information is data that
exists after a session ends. In HTML5, developers can use the localStorage
and sessionStorage JavaScript methods to deal efficiently with state data. In
addition, AppCache enables a user to load data ordinarily stored on a server
even when the user is offline.
Storing State Data Using Local and Session Storage

When we enter a uniform resource locator (URL) into the address


bar of a browser, the browser sends an HTTP request to a Web server for a
Web page.

HTTP is short for Hypertext Transport Protocol. HTTP is a


stateless protocol, which means that it doesnt retain data from session to
session.
Therefore, when we close a Web browser after using an application,
data is not automatically saved.

To work around the limitations of HTTP protocol, developers


historically have used cookies, which are small files that contain information
about the user and the Web site visited and are saved on the users computer.
When a user returns to a visited site, the browser sends the cookies back to
the Web server. Cookies help a Web server remember a user and customize
the users experience on that site.
However, cookies have proven to be a security risk. In addition, if
large amounts of data are involved, all the data gets sent between the browser
and server upon every request, which would cause a noticeable performance
decrease to the user.
In HTML5, developers can use the Web storage instead, which offers
more flexibility, larger data sets, and better performance. The localStorage
method allows users to save larger amounts of data from session to s ession
(persistent data), and theres no time limit as to how long the data exists.

The SessionStorage method keeps data only for one session (until the
browser is closed), which is also referred to as per-tab storage. Using these
methods, specific data is transferred only when requested, so its possible to
store a relatively large amount of data without slowing down the connection
or site.

Appcache for offline files

Another way to use Web storage is to store data locally when a user is
offline. The Application Cache, or AppCache, stores resources like images,
HTML pages, CSS files, and JavaScript - data that would ordinarily be stored
on a server. Because the resources are stored on the clients hard disk or
device, the resources load faster when requested.
Using AppCache, a developer uses a text file called a cache
manifest to specify the files a Web browser should cache offline. Even if a
user presses the Refresh button offline, the app will load and work correctly.
6 - Touch Interfaces and Gestures
Todays mobile devices and many PC monitors incorporate touch-
screen technology, which makes it easier for many users to interact with the
devices and their programs. A simple finger tap selects an object or presses a
button, a finger swipe scrolls a list of photos on the screen, and a pinch
zooms out on an image.

Any finger move is referred to as a gesture, which can involve a


single finger (one-touch, such as press, tap, press and hold, slide to pan, and
so on) or a finger and a thumb (two-touch, such as a pinch and stretch or a
turn to rotate). The action the application takes in response to a gesture is
called a touch event.
You can use JavaScript to create touch events in touch enabled apps.
In JavaScript, the three primary touch events are touchstart, touchend, and
touchmove. We will learn more in chapter 31.

When developing any touch-enabled app, be sure to test for the


following:
- Overall responsiveness and fluidity
- Tapping, pinching, rotating, and other common gestures
- Controlled scrolling
- Controlled panning
- Ability to disabled scrolling and panning
- Accuracy of snap points
- Unintended zooming or scrolling, especially in a multi-touch environment
- Proper touch event reaction, especially in a multi-touch environment

Designing and developing well-formed touch-enabled apps takes


practice, and a lot of testing. If you dont have a touch-screen device, you can
use MouseTouch events and a touch-screen emulator or simulator. Try
Microsoft Surface SDK and Runtime for Windows 7, or the Windows
Simulator tool in Visual Studio 11. A touch-screen simulator or emulator
imitates a system that only has touch capabilities. Several free emulators are
available online.
7 - Debugging and Testing
All apps must be thoroughly tested and debugged to ensure they run
reliably and as error free as possible before distribution and deployment.

Debugging is the process of detecting, finding, and correcting errors


in logic and syntax
- Logic errors prevent the app from behaving as expected
- Syntax errors are typos in code which prevent Web apps from running

Testing and debugging code is a standard part of app development,


and most tools like Visual Studio have debugging features built in to the
software. Some errors are easy to detect and fix, whereas others can require
hours or even days to resolve, depending on the complexity of the
application.
8 - Validating HTML5 Code
An important aspect of debugging and testing is to validate code to
ensure it is properly interpreted by browsers.
We can use a validator to test code for inaccuracies and syntax
errors.

W3C provides a code validation service for all versions of HTML and
CSS at https://validator.w3.org/

Validating a Package

Packaging an app is the process of preparing an app for installation on


different devices or systems.
Microsoft provides a free tool called the Windows App Certification
Kit for testing local apps. The kit is a type of validator that tests your app on
your computer before you attempt to package and publish it to the Windows
Store.
9 - Publishing an Application
After you test, debug, and validate your code, it will be ready for
upload to a marketplace for apps. If the app was built for Windows, then the
marketplace will be the Windows Store.

Publishing your app to a public marketplace like the Windows Store


is the pinnacle of all your planning, designing, coding, and testing. The
Windows Store is an online global marketplace for Metro style apps.
Publishing your app for distribution through the store can possibly turn a
good idea into a lucrative venture.
Before publishing an app to the Windows Store, you must:
- Sign up and pay for a developer account
- Go through the app submission checklist
- Capture screenshots of unique features in your app
- Have other users test your app on multiple devices and platforms
- Include a privacy statement if your app gathers personal information or
copyrighted software
10 - HTML Essentials
HyperText Markup Language (HTML) is the standard markup
language for creating web pages and web applications.

HTML markup consists of several key components, including those


called tags (and their attributes), character-based data types, character
references and entity references. HTML tags most commonly come in pairs
like <h1> and </h1> , although some represent empty elementsand so are
unpaired, for example <img> . The first tag in such a pair is the start tag, and
the second is the end tag (they are also called opening tags and closing tags).
Basic Markup and Page Structure

Using Attributes
Tags are used in combination with attributes to describe how data
should be rendered on a Web page. In other words, attributes can be used to
provide additional information that tags cannot provide alone. Each element
has a specific set of attributes that can be used with it.

HTML5 includes global attributes, which can be used with any


element.
Attributes are added to tags using the following syntax:

Nesting Elements

Creating awesome web pages requires you to combine elements, their


attributes, and engaging content
When two or more elements apply to the same block of content, then you
must nest the tag pairs.

Nesting is the process of placing one element inside of another.

The outside element is called a parent, while the inner element is


called a child.

Understanding entities
An entity is a special character, such as the dollar symbol, the
registered trademark (a capital R within a circle), and accented letters.

The DOCTYPE

A doctype declaration is used to help a Web browser determine


which rules it should use for rendering a Web page.
In HTML 4, doctype declarations require a reference to a Document
Type Definition (DTD) and looks quite complex.

In HTML5, the doctype declaration is simpler, as shown below.


<!doctype html>

Deprecated Elements
As new standards are released from the W3C there are also elements
that will no longer be supported by the W3C standards and therefore
browsers will eventually stop displaying deprecated elements.

The following HTML elements are considered deprecated and are not
supported in HTML5 pages.

HTML5 Tags to Display Graphics

Images are an incredibly important aspect of creating engaging Web


pages. There are two major categories of images that can be used:
- raster (bitmap)
- vector
Raster images are made up of pixels, while vector images are made of
lines and curves.

The primary way to add images to an HTML document is with the


img element.
<img src="img_path" alt="alt_atribute" height="42" width="42">

The <img> tag requires the use of the src and alt attributes:
- src stands for source (src defines the pathway for the image file)
- alt stands for alternative (the value of the alt attribute makes text
accessible to people with disabilities)

The img element can uses several attributes:

figure and figcaption

The img element can be used in combination with two new elements,
figure and figcaption, to organize images and provide captions.
The figure element specifies the type of figure that is being added,
and can also be used to group images side by side.

The figcaption element can be used to add captions before or after


images.
<figure>
<img src="doghappy.jpg" alt="Happy dog" width="100" height="125" />
<figcaption>Happy dogs are good dogs
</figcaption>
</figure>
The canvas Element
The canvas element creates a blank container for graphics. Its a new
element in HTML5 and you can draw graphics using JavaScript.

Drawing on a canvas is done by using the Canvas API. Canvas can is


used by developers to create 2D games or animations

Creating an outline of a shape

To create an outline of a rectangle without a fill color, use the


context.strokeRect method. It uses the same values as context.fillRect. To
modify the color of the outline (the stroke color), use context.strokeStyle.
For example, to create a 200 x 100 pixel rectangular outline in red, use these
methods in your JavaScript:
context.strokeStyle = "red";
context.strokeRect(10,20,200,100);

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas Test</title>
<script>
function f1() {
var canvas =document.getElementById("smlRectangle");
context = canvas.getContext("2d");
context.strokeStyle = "red";
context.strokeRect(10,20,200,100);
}
</script>
</head>
<body onload="f1();">
<canvas id="smlRectangle"> </canvas>
</body>
</html>

Some older browsers cannot render canvas drawings or animation.


Therefore, you should add an image, text, or some other HTML content
within the canvas element that will display if the drawing cannot.

Scalable Vector Graphics


Scalable Vector Graphics (SVG) is a language for describing 2D
graphics in XML. With SVG, you provide drawing instructions within your
code versus using the src attribute to point to a file. Unlike other image types,
graphics created using the svg element are scalable. The quality of the image
will not change if it shrinks or is enlarged.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>SVG</title>
</head>
<body>
<svg id="svgpurpball" height="200" xmlns="http://www.w3.org/2000/svg">
<circle id="purpball" cx="40" cy="40" r="40" fill="purple" />
</svg>
</body>
</html>

Canvas vs. SVG

Canvas Scalable Vector


Graphics
- Use for small - Use for larger
drawings graphics
- Use for drawings - Use for drawings
with a lot of objects with a small number
in them of objects
- Use for small - Use for drawings
screens that require a large
number of pixels
- Use for real-time - Use for highly
data output, such as detailed vector
maps or weather graphics
data

HTML5 Tags to Play Media

HTML5 introduces the audio and video elements, which do away


with the need for plug-ins or media players to listen to music or watch videos
via a Web browser.

The video element enables you to incorporate videos in HTML


documents using minimal code. The structure for embedding video is simple.
The following is an example of the markup for adding an MP4 file to a Web
page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Video Test</title>
</head>
<body>
<video width="400" height="300" poster="sample.png" autoplay="autoplay" controls="controls">
<source src="sample.mp4" type="video/mp4" />
</video>
</body>
</html>

The audio element enables you to incorporate audio, such as music


and other sounds, in HTML documents. You can include the same control-
related attributes as the video element: autoplay, controls, and loop. The
following example shows just the controls attribute included:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Audio Test</title>
</head>
<body>
<audio src="sample.mp3" controls="controls"> </audio>
</body>
</html>
11 - Organize Content
To improve the structure of your web pages, you need HTML5s new
semantic elements. The names of these tags are representative of semantic
markup.

In HTML 4.01 and before, developers had to rely on the use of the
<div> tag to perform a variety of functions. The <div> tag often includes a
class or id attribute, which may also include CSS styles such as background-
color, height, and width.
- class and id are global attributes, which means that they can be used with
all HTML elements
- class is used to identify a group of elements
- id is used to identify individual elements

A simple example of a <div> tag is: <div id="header"> This is a header </div>

Markup in HTML 4.01 vs. HTML5

HTML5 offers new semantic elements to define different parts of a


web page:
Structural Tags

The <header> and <footer> elements

The <header> element specifies a header for a document or section.


A header typically features titles, logos, or photos and may be the first thing a
user sees upon visiting a site

The <footer> element specifies a footer for a document or section. A


footer typically contains the author of the document, copyright information,
links to terms of use, contact information, etc.

You may have several <footer> and <header> elements in one


document.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<header>
<<h1>Learning HTML5</h1>
<h2>Semantic Elements</h2>
</header>
<p>Super HTML5 tags</p>
<footer>
<p>Posted by: AnySolution</p>
<p>Contact information:<a href="mailto:contact@anysolution.ro">contact@anysolution.ro</a>.
</p>
</footer>
</body>
</html>

The <section> element

The <section> element defines a section in a document. According to


W3C's HTML5 documentation: "A section is a thematic grouping of content,
typically with a heading."
A home page could normally be split into sections for introduction,
content, and contact information. However, there are situations in which you
should not use the section element:
The <hgroup> element
The <hgroup> element is used to group headings. This allows you to
organize heading tags, but wont impact the way things look on a web page.
<section>
<hgroup>
<h1>HTML5</h1>
<h3>Structuring a Web page</h3>
</hgroup>
<article>
<p>With semantic tags, structuring a web page is easier!</p>
</article>
</section>

The <nav> element

The <nav> element is used to organize links that allow users to


navigate from one page to another. The <nav> tag shouldnt be used for
every link on a page, but rather to group the links together.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
</nav>
</body>
</html>
The <article> and <aside> elements
The <article> element specifies independent, self-contained content.
An article should make sense on its own, and it should be possible to read it
independently from the rest of the web site.

Examples of where <article> can be used:


- Forum post
- Blog post
- Newspaper article
The <aside> element defines some content aside from the content it is
placed in (like a sidebar). The aside content should be related to the
surrounding content.

Tables and Lists

An HTML table is defined with the <table> tag. Each table row is
defined with the <tr> tag. A table header is defined with the <th> tag. By
default, table headings are bold and centered. A table data/cell is defined with
the <td> tag.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<caption>Number of hours worked on writing the second HTML5 manual.</caption>
<table border="1">
<tr>
<th>Month</th>
<th>Hours</th>
</tr>
<tr>
<td>September</td>
<td>100</td>
</tr>
<tr>
<td>October</td>
<td>45</td>
</tr>
<tr>
<td>November</td>
<td>120</td>
</tr>
</table>
</body>
</html>

Common table tags

Tag Description
<table> Defines a table
<th> Defines a header cell in a table
<tr> Defines a row in a table
<td> Defines a cell in a table
<caption> Defines a table caption
Specifies a group of one or more columns in a table for
<colgroup>
formatting
Specifies column properties for each column within a
<col>
<colgroup> element
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table

There are two primary types of lists in HTML5: ordered and


unordered. Ordered lists use the <ol> tag and order items in a list using
numbers. Unordered lists use the <ul> tag and display items in a bulleted list.
You can add items to both types of lists using the <li> tag.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
</body>
</html>
12 - Input and Validation
Developers use Web forms as the interface to collect information
from Web site and client application users. HTML input elements serve to
build a forms interface and ensure that information is collected from users
consistently. Validation ensures that the entered information is in the correct
format and usable before sending the data to the server.

In HTML, input and validation apply to forms.


Web Forms

A Web form is a page that features input fields where users enter
data. Form input, or the data supplied by users, is sent to a server where it is
processed and stored. Web forms are commonly used when making
purchases, signing up for newsletters, or completing surveys.

The HTML <form> element defines a form that is used to collect user
input. An HTML form contains form elements.
Form elements are different types of input elements, like text fields,
checkboxes, radio buttons, submit buttons, and more.

The <label> element displays a label for each field.

The <input> element is used to dictate the type of input that is


expected
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="contact" method="post" action="">
<label for=firstName">First Name</label> <br/>
<input type="text" name=firstName" /><br />
<label for=lastName">Last Name</label> <br/>
<input type="text" name=lastName" /><br />
<label for="email">Email</label> <br />
<input type="email" name="email" /><br />
</form>
</body>
</html>

Input Attributes

There are several attributes that can be used with the <input> element
to enhance Web forms:
- the autofocus attribute to point the focus to a specific input field when a
web page loads
- the required attribute when a field is required
- the placeholder attribute to add text to a field that will help users know
what to enter
- value attribute specifies the initial value for an input field
- readonly attribute specifies that the input field is read only (cannot be
changed)
- disabled attribute specifies that the input field is disabled
- size attribute specifies the size (in characters) for the input field
- maxlength attribute specifies the maximum allowed length for the input
field
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Form Demo!</h1>
<form id="contact" method="post" action="">
<label for=firstName">First Name</label>
<input type="text" name=firstName" placeholder="First Name" /><br />
<label for=lastName">Last Name</label>
<input type="text" name=lastName" placeholder="Last Name" /><br />
<label for="email">Email</label>
<input type="email" name="email" placeholder="Email Address" /><br />
<label for="password">Password</label>
<input type="password" name="password" placeholder="Password" /><br />
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>

Form Validation

Validation is the process of verifying that the information obtained


from a form is in the appropriate format.
Common issues that arise with forms are:
- empty fields
- invalid email addresses
- invalid dates
- text vs. numbers and vice versa

In HTML 4.01, validation required the use of JavaScript, but HTML5


now offers automatic validation. This is referred to as client-side
validation, because the input data is validated before submission to the
server (if validation is performed by a server, then its called server-side
validation).
If a user enters the wrong value into a form field, then the browser
will instruct them to correct the error. The browser determines if the data is
valid by reading attributes in the forms tags, such as the pattern attribute.

The required attribute avoids the problem of empty fields that need
to be populated. When a user skips a required field, and clicks the submit
button, an error message appears.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Form Demo!</h1>
<form id="contact" method="post" action="">
<label for=firstName">First Name</label>
<input type="text" name=firstName" placeholder="First Name" required /><br />
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
13 - CSS Introduction
CSS comes from Cascade Style Sheets. It is the language used to
format web pages (text, background or layout, etc.).

In other words, HTML structures a document, while CSS formats it.


CSS can be applied to single HTML elements, or it can be kept in a separate
file and applied to elements throughout a document. Files that hold CSS are
called style sheets and use the .css extension. Unlike HTML, CSS uses
rules instead of tags.

CSS code can be written in three ways: inline, internal, external.

1. Inline - directly into the HTML tag

<p style="color: red">

2. The <style> element nested in the <head> element


<style>
h1 {
font-family: 'Segoe UI';
color: #808080;
}
</style>
3. The <link> element and a separate CSS file
<link href="StyleSheet.css rel="stylesheet" type="text/css">

Placing CSS in a separate file has a lot of advantages:


- A style change can apply to an entire document
- Teams working on Web projects can separate responsibilities

CSS files are linked to HTML files using the <link> element. The href
attribute points to the location of the CSS file. Its extremely important that
the file name and location are correct or none of the style will be applied. The
rel attribute should be set as stylesheet, while the type attribute should be
set as text/css.
<!DOCTYPE html>
<html>
<head>
<title>Page title</title>
<link href="example.css" rel="stylesheet"
type="text/css">
</head>
<body>
<h1>This is a header</h1>
<p>This is a paragraph</p>
</body>
</html>

In a second file, in the same folder as the .html source; in the file
named example.css we have:
h1 {
font-size: 20px;
color: green;
font-style: italic;
}

The index .html file in a Web browser should look like the below picture:
14 - CSS Sintax
There are two parts to a CSS rule:
- selectors
- declarations

The selector is usually the HTML element you want to style.


The declaration is the style for a specific selector.
- declarations have two parts: a property followed by a colon (:) and a space,
and a value followed by a semicolon (;)
- declarations sit between curly brackets {}

The main types of CSS selectors are:


element selector (HTML) such as p, h1, table, etc.
h1 {
color: red;
font-family: sans-serif;
text-align: left;
}
class selector like .happy, which include a decimal (.) as a prefix
.happy {
font-size: 14px;
}
id selector such as #para1, which include a hashtag symbol (#) as a prefix
#para1 {
background-color: green;
}

Note: Id and class are both universal attributes.

Id is used to identify unique elements, class should be used to


categorize elements into groups that will be styled similarly.
<!DOCTYPE html>
<html>
<head>
<title>Page title</title>
<link href="example.css" rel="stylesheet"
type="text/css">
</head>
<body>
<h1>This is a header</h1>
<p id="para1" >This is a paragraph</p>
<p>This is a paragraph</p>
</body>
</html>

In the .css file we have all three selectors.


h1 {
color: red;
font-family: sans-serif;
text-align: left;
}
.happy {
font-size: 14px;
color: blue;
}
#para1 {
background-color: green;
}

The index .html file in a Web browser will look like the below picture:

CSS Comments
Content between /* and */ in a CSS file is called a comment. Its a
note inserted by the developer for informational purposes only and it doesnt
affect the CSS or Web page.

Comments can appear anywhere in a style sheet.


/*These comments are typically reserved for making multi-line comments*/
p{
color: red;
/* This is a single-line comment */
text-align: center;

Fonts and Font Families

A font is a set of characters of a particular size and style. The primary


way to specify fonts in CSS is by using the font-family property. Three
common types of fonts are serif, sans serif, and monospace.
@font-face rule
Web fonts allow Web designers to use fonts that are not installed on
the user's computer.
When you have found/bought the font you wish to use, just include
the font file on your web server, and it will be automatically downloaded to
the user when needed.

Your "own" fonts are defined within the CSS3 @font-face rule.
@font-face {
font-family: myFirstFont;
src: url(http://website/fonts/fontfile);
}
15 - Managing Content
Content Flow

The content flow can be managed in an HTML document using inline


flow and block flow properties in CSS.

With block flow an element occupies the entire width available. With
inline flow an element occupies only the available width. We could say that
inline flow fits and block flow separates .

For example the <li> list item element, is a block element.


<!doctype html>
<html>
<head>
<title>Block and inline flow</title>
<link href="example.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Block and inline flow</h1>
<p><em>List item</em> is a block element, that we can display as an inline element, using CSS.
</p></br>
<ul class="toolbar">
<li>HTML</li>
<li>PHP</li>
<li>JAVA</li>
<li>CSS</li>
</ul>
</body>
</html>

Using CSS, we can display it as an inline element.


.toolbar li {
display:inline;
background-color: green;
border: 1px solid;
border-color: #F3F3F3 #BBB #BBB #F3F3F3;
margin: 2px;
padding: .5em;
}

Positioning

The position property specifies the type of positioning method used


for an element (static, relative, absolute or fixed).

static positions an element within its


normal flow
relative positions an element in relation to
where it would normally be
positioned in the flow of content
absolute ensures that the positioning of an
element doesnt impact other
content
fixed positions an element in relation to
the browser window and stays in
the same place
initial sets this property to its default
value
inherit inherits this property from its
parent element

An absolute position of an element it means that it is positioned


relative to the nearest ancestor.
<!doctype html>
<html>
<head>
<title>No title</title>
<link href="example.css" rel="stylesheet" type="text/css">
</head>
<body>
<p id="col1">=Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet
felis. Integer sit amet diam. Phasellus ultricesviverra velit. </p>
<p id="col2">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet
felis. Integer sit amet diam. Phasellus ultrices viverra velit.</p>
<p id="col3"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet
felis. Integer sit amet diam. Phasellus ultrices viverra velit.</p>
</body>
</html>

The origin (0,0 coordinate point) is the upper left corner of the
window or object that contains the element positioned absolutely.
#col1 {
position: absolute;
bottom: 100px;
right: 100px;
background-color: lightskyblue;
}
#col2 {
background-color: yellow;
}
Resize the window and see how the three different paragraphs adjust.

Floating Elements

The float property allows you to move an element all the way to the
left or right of a page, other content will wrap around the floated content. The
value of float is commonly set to left or right.

none The element is not floated, and will


be displayed just where it occurs in
the text
left The element floats to the left
right The element floats the right
initial Sets this property to its default value
inherit Inherits this property from its parent
element

Float positioning often is useful when a layout is in columns.


<!doctype html>
<html>
<head>
<title>No title</title>
<link href="example.css" rel="stylesheet" type="text/css">
</head>
<body>
<p id="col1">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet
felis. Integer sit amet diam. Phasellus ultrices viverra velit.</p>
<p id="col2">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet
felis. Integer sit amet diam. Phasellus ultrices viverra velit.</p>
<p id="col3">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet
felis. Integer sit amet diam. Phasellus ultrices viverra velit.</p>
</body>
</html>

In the browser, col1 and col2 appear as two fixed-width columns, and
col3 fills up any remaining space.

Clearing a Float
Use the clear property to prevent other floating elements from
touching the left or right hand sides of an element. The value of the clear
property can be left, right, both, or none.
- left clears the left side
- right clears the right side
- both clears both sides
- none allows other elements to touch
Overflow
Every HTML element on a page occupies a rectangular space called a
bounding box. With CSS, you can modify the height or width of the
bounding box.

If an element doesnt fit inside of its bounding box, then that content
is called overflow.
The overflow property specifies whether to clip content or to add
scrollbars when the content of an element is too big to fit in a specified area.

The overflow property has the following values:


- visible - Default. The overflow is not clipped. It renders outside the
element's box
- overflow - The overflow is clipped, and the rest of the content will be
invisible
- scroll - The overflow is clipped, but a scrollbar is added to see the rest of
the content
- auto - If overflow is clipped, a scrollbar should be added to see the rest of
the content
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
div {
float: left;
}
#col1 {
background-color: #eee;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow: visible;
}
#col2 {
background-color: pink;
width: 200px;
height: 50px;
border: 1px dotted black;
overflow: hidden;
}
#col3 {
background-color: yellow;
width: 200px;
height: 100px;
border: 1px dotted black;
overflow: scroll;
}
#col4 {
background-color: grey;
width: 200px;
height: 100px;
border: 1px dotted black;
overflow: scroll;
}
</style>
</head>
<body>
<div>
<p>Visible</p>
<p id="col1">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit
amet felis. Integer sit amet diam. Phasellus ultrices viverra velit. Pellentesque habitant morbi tristique
senectus et netus et malesuada fames ac turpis egestas.</p>
</div>
<div>
<p>Hidden</p>
<p id="col2">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit
amet felis. Integer sit amet diam. Phasellus ultrices viverra velit. Pellentesque habitant morbi tristique
senectus et netus et malesuada fames ac turpis egestas.</p>
</div>
<div>
<p>Scroll</p>
<p id="col3">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit
amet felis. Integer sit amet diam. Phasellus ultrices viverra velit. Pellentesque habitant morbi tristique
senectus et netus et malesuada fames ac turpis egestas.</p>
</div>
<div>
<p>Auto</p>
<p id="col4">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit
amet felis. Integer sit amet diam. Phasellus ultrices viverra velit. Pellentesque habitant morbi tristique
senectus et netus et malesuada fames ac turpis egestas.</p>
</div>
</body>
</html>
16 - Layouts
The User Interface (UI)
The portion of a Web page where users interact is called the user
interface (UI).

The layout of a user interface will dramatically impact a user


experience.

Layouts can range from minimalist with just a few elements, to pages
that are jammed full of content. Simple layouts and complex layouts require
different models to ensure that content displays properly for users.

To help ensure that CSS3 styles work during this transition phase,
many of the major Web browsers offer alternative property names. These
workarounds simply add a vendor prefix , which is a keyword surrounded by
dashes, to the front of a CSS3 property name. Keep the following in mind as
you work with CSS3 properties:
- Internet Explorer uses the -ms- prefix.
- Firefox supports the -moz- prefix.
- Opera supports the -o- prefix.
- Chrome and Safari support the -webkit- prefix.
For example, to apply the flexbox style to elements in a

browser, like Chrome, you simply add the -webkit-flexbox property to your

CSS.

The traditional CSS Box model

The CSS box model is essentially a box that wraps around every
HTML element. It consists of: margins, borders, padding, and the actual
content.
- Content - The content of the box, where text and images appear
- Padding - Clears an area around the content. The padding is transparent
- Border - A border that goes around the padding and content
- Margin - Clears an area outside the border. The margin is transparent

Block-level and Inline Elements

Within the CSS Box model, there are two categories of elements
- block-level
- inline
Block-level elements create boxes that are a part of a pages layout.
This category includes articles, sections, paragraphs, headers, footers and
more.

Examples of block-level elements:


- <div>
- <h1> - <h6>
- <p>
- <form>

Inline elements are used to format content


this category includes emphasis and boldface.
Examples of inline elements:
- <span>
- <a>
- <img>

Parent and child boxes

With the CSS Box model, it is possible for a box to contain one or
more boxes:
- The outer box is referred to as the parent
- An inner box is referred to as a child

A child inherits CSS styles from a parent, which means that styles
applied to a parent will apply to a child as well.

Flexbox

Flexible boxes, or flexbox, is a new layout mode in CSS3. Use of


flexbox ensures that elements behave predictably when the page layout must
accommodate different screen sizes and different display devices.

For many applications, the flexible box model provides an


improvement over the block model in that it does not use floats, nor do the
flex container's margins collapse with the margins of its contents.
Elements, navigation bars, forms and pictures will resize and
reposition automatically to fill available space.

We use media queries to determine which device is being used. CSS


uses this information to automatically adjusts our HTML document to fit a
screen.

Flexbox layout is similar to block layout, but flexbox doesnt use


columns or floats. In
addition, whereas block layout typically lays out content vertically (and inline
layout tends to lay out content horizontally), a flexbox resizes in either
direction.

Flexbox Concepts
Flexbox consists of flex containers and flex items. A flex container is
declared by setting the display property of an element to either flex (rendered
as a block) or inline-flex (rendered as inline).

Inside a flex container there is one or more flex items. Flex items are
positioned inside a flex container along a flex line. By default, there is only
one flex line per flex container.
The following example shows three flex items. They are positioned
by default: along the horizontal flex line, from left to right:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
<div class="flex-item">flex item 3</div>
</div>
</body>
</html>
If we set the direction property to rtl(right-to-left), the text is drawn
right to left, and the flex line changes direction, which will change the page
layout:
<!DOCTYPE html>
<html>
<head>
<style>
body {
direction: rtl;
}

.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}

.flex-item {
background-color: cornflowerblue;
width: 100px;
height: 100px;
margin: 10px;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">flex item 1</div>
<div class="flex-item">flex item 2</div>
<div class="flex-item">flex item 3</div>
</div>
</body>
</html>

The following table lists the CSS properties used with flexbox:
Specifies the type of box used for an HTML
display element
flex- Specifies the direction of the flexible items
direction inside a flex container
Horizontally aligns the flex items when the
justify- items do not use all available space on the
content main-axis
Vertically aligns the flex items when the
items do not use all available space on the
align-items cross-axis
Specifies whether the flex items should wrap
or not, if there is not enough room for them
flex-wrap on one flex line
Modifies the behavior of the flex-wrap
property. It is similar to align-items, but
align- instead of aligning flex items, it aligns flex
content lines
A shorthand property for flex-direction and
flex-flow flex-wrap
Specifies the order of a flexible item relative
to the rest of the flex items inside the same
order container
Used on flex items. Overrides the container's
align-self align-items property
Specifies the length of a flex item, relative to
the rest of the flex items inside the same
flex container

Changing the Direction of Child Items

The flex-direction property allows developers to change the direction


of child boxes in a flexbox. It uses the row, row-reverse, column, and
column-reverse values.

The flex-wrap property determines if child boxes will wrap onto a


new line when a window condenses. It uses the nowrap, wrap, and wrap-
reverse values.
The flex-flow property sets the flex-direction and flex-wrap
properties at the same time.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Flex-flow Example</title>
<style>
div {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
height: 400px;
padding: 1em;
outline: 2px solid silver;
color: white;
font-family: sans-serif;
font-weight: bold;
}
p{
width: 100px;
margin: 1em;
height: 100px;
background-color: dodgerblue;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div>
<p>Child1</p>
<p>Child2</p>
<p>Child3</p>
</div>
</body>
</html>

To reverse the order of the child boxes, change each of the flex-
direction column values to column-reverse:
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column-reverse;
flex-direction: column-reverse;
Ordering and Arranging Content
The order property allows you to adjust the order and arrangement of
contents inside of a flexbox.
The property groups child boxes to control the order in which they
appear in a layout. The default value for the flex-order property is 0.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
div {
display: -webkit-flex;
display: flex;
height: 400px;
padding: 1em;
outline: 2px solid silver;
color: white;
font-family: sans-serif;
font-weight: bold;
}
p{
width: 100px;
margin: 1em;
height: 100px;
background-color: dodgerblue;
text-align: center;
line-height: 100px;
}
.first {
-webkit-order: -1;
order: -1;
}
</style>
</head>
<body>
<div>
<p>Child1</p>
<p class="first">Child2</p>
<p>Child3</p>
</div>
</body>
</html>

The Grid Layout Model

When the Flexbox Box model isnt appropriate, you can use the Grid
Layout model.
The Grid Layout model uses CSS to structure content using rows and
columns. Grids are extremely flexible and provide an easier to use option for
organizing content than HTML tables.

Grid layouts are similar to spreadsheets in that they use columns,


rows, and cells, but you can create many different types of layouts that, in the
end, dont look like a spreadsheet at all.

Define a grid layout by using the display property, along with the
grid or inline-grid values.
Child elements in a grid are called grid items, which can be positioned
according to grid tracks, grid lines, or grid cells.
- Grid tracks: The columns and rows of the grid; you define grid tracks
using the grid-rows and grid-columns properties
- Grid lines: The horizontal and vertical lines that divide columns or rows
- Grid cells: The logical space used to lay out grid items, similar to a cell in a
spreadsheet
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Grid Example</title>
<style>
#gridded {
display: grid;
grid-columns: 10px 250px 10px 250px 10px 250px 10px 250px 10px;
grid-rows: 1fr;
}
#item1 {
background: orange;
grid-row: 1;
grid-column: 1;
}
#item2 {
background: purple;
grid-row: 2;
grid-column: 2;
color: white;
}
</style>
</head>
<body>
<div>
<div id="gridded">
<div id="item1">Logo</div>
<div id="item2">Item</div>
</div>
</div>
</body>
</html>
17 - Managing Text Flow
CSS Regions
CSS Regions are sections of a document where content can flow from
one region to another. If there is too much content in one section, then the
remaining content automatically flows into another region.

Regions can be placed anywhere on a screen and you can control the
order in which the flowed content appears.

Creating a CSS Region, you must specify a content source and


content containers. You set up CSS regions with the flow-into and flow-
from properties.
A content source is a chunk of text that holds the content you want to
flow through the regions.

Content containers are the areas where you want your content to
appear.
<div id="content" src="content.html"></div>
<div id="region1" class="region"></div>
<div id="region2" class="region"></div>
<div id="region3" class="region"></div>

Using an id as a selector, identify the content source using the main


value of the flow-into property. This content will require content containers
to appear on a Web page. With a specific class as the selector, use the same
value used with the flow-into property for the value of the flow-from
property to place content into a container. This is how the source and content
containers are associated.
#content {
-ms-flow-into: main;
}
.region {
-ms-flow-from: main;
background: #9ACD32;
width: 150px;
height: 200px;
float: left;
margin: 20px;
}

Overflowing Text
The height of a region wont automatically adjust to fit all content.
Height of regions must be defined.

If there is content available after all regions have been filled, then the
last region will:
- be cut off
- visibly overflow
- overflow and be hidden

The overflow and region-fragment properties can be used to control


how overflow content is treated.
- set region-fragment to auto or break
- set overflow to visible or hidden
Microsofts method of implementing CSS Regions varies a bit from
the W3C version described previously. Microsoft uses iframes , which are
like mini boxes on a Web page that contain external content embedded in an
HTML document, as the content source.
You must also use the -ms- vendor prefix with the flow-into and
flow-from properties.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link href="StyleSheet.css" rel="stylesheet" type="text/css">
<title>Overflow Examples</title>
<style>
#content {
-ms-flow-into: main;
}
.region {
-ms-flow-from: main;
-ms-region-fragment: auto;
overflow: visible;
background: #0ff;
width: 150px;
height: 200px;
float: left;
margin: 20px;
}
</style>
</head>
<body>
<h1>CSS Regions</h1>
<iframe id="content" src="content.html"></iframe>
<div id="region1" class="region"></div>
<div id="region2" class="region"></div>
<div id="region3" class="region"></div>
</body>
</html>
<!--The code for content.html is located below -->

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed efficitur sapien. Nunc
pellentesque eget turpis at blandit. Sed at sapien sed dolor posuere sodales. Sed non pulvinar purus.
Morbi bibendum enim quis leo tempus, vitae accumsan lacus tincidunt. Integer pulvinar tortor vitae
magna gravida ullamcorper. Vestibulum eget sapien metus. Mauris tempor faucibus vehicula. Aliquam
finibus sed libero eget congue.</p>
<p>Phasellus fringilla a lacus quis tempor. Nulla quis commodo purus. Integer vitae orci quis quam
congue scelerisque. In sodales augue tellus, id ullamcorper felis aliquet molestie. Fusce sodales semper
augue id varius. Suspendisse lobortis cursus dolor eu tincidunt. Praesent et tortor a quam auctor
tincidunt non ac odio. In varius, felis et molestie eleifend, ante justo rhoncus dui, vel aliquet enim ligula
vel dui. Sed at efficitur tortor. Praesent interdum cursus ex vel ullamcorper.</p>
</body>
</html>

Columns and Hyphenation

CSS3 enables you to create multi-column layouts that work much like
the columns feature in Microsoft Word.
There are three primary CSS properties that you can use to manipulate
columns:
- column-count
- column-gap
- column-rule

In the CSS Box, columns are in between the content and the Box.
Column Properties
Hyphenation
You can also enable hyphenation to properly break words at the end
of lines, which avoids the problem of long words wrapping to the next line
and leaving a gap on the previous line.
.hyphenized {
-moz-hyphens: auto;
-ms-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}

The property uses the values none, manual, and auto:


- auto: Enables automatic hyphenation of words based on line-break
opportunities within words or by a language-appropriate hyphenation
resource
- manual: Enables hyphenation of words based only on line-break
opportunities within words
- none: Prevents hyphenation

The W3C points out that you must declare a language using the
HTML lang or XML xml:lang attributes for correct automatic hyphenation to
occur.

That means if your entire HTML document is in the same language


(English, for example) and you want to enable automatic hyphenation, add
the attribute to your HTML element or doctype declaration, such as:
<!DOCTYPE html>
<html lang="en">

or
<html xmlns=http://www.w3.org/1999/xhtml xml:lang="en" lang="en">

CSS Exclusions

A positioned float is a CSS construct that enables you to position


images, text, and boxes anywhere in an HTML document and then wrap text
completely around these elements. Positioned floats are called CSS
Exclusions in the latest W3C specification.

CSS Exclusions allow you to specify positioning from the top,


bottom, left, and right of a container. Exclusions can also be created in a
variety of shapes.

Declare an exclusion by using the wrap-flow property with the


preferred value. Modify the shape of an exclusion using the shape-outside
and shape-inside properties.
CSS Exclusions may not be supported by all the major browsers. Use
vendor prefixes and experiment with as many browsers as possible to make
sure the content renders properly.
18 - Managing the Graphical Interface
CSS3 enables you to create stunning graphical elements for Web sites
and applications, which ratchet up the satisfaction of the user experience.
You can create graphics effects such as rounded corners and drop
shadows, and apply 2D and 3D transformations like rotations and7scaling.

Transitions and animations, performed completely with HTML and


CSS3, bring life to otherwise static images, boxes, and text.
Rounded Corners

In CSS3, you can add rounded corners to layout elements, including


headers, footers, sidebars, and images. Use the border-radius property along
with a length value, such as pixels, ems, or a percentage.
- the higher the value, the more rounded a corner will be
- some browsers have problems rendering a percentage value

You can round individual corners with the following properties:


- border-top-left-radius
- border-top-right-radius
- border-bottom-right-radius
- border-bottom-left-radius
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#rcorners {
border-radius: 15px 50px 30px;
background: #73AD21;
padding: 20px;
width: 200px;
height: 150px;
}
</style>
</head>
<body>
<p id="rcorners">Rounded corners!</p>
</body>
</html>

Creating Shadows

Add drop shadows to elements using the box-shadow property. A


drop shadow is a visual effect that makes an object appear like it is floating
above other objects on a document.
There are six attributes that can be modified when using the box-
shadow property: h-shadow, v-shadow, blur, spread, color, and inset.

The h-shadow and v-shadow attributes must be included, while the


others are optional.
<!DOCTYPE html>
<html>
<head>
<titile></titile>
<style>
#box {
box-shadow: 10px 10px 5px #808080;
background: #73AD21;
padding: 20px;
width: 150px;
height: 100px;
}
</style>
</head>
<body>
<p id="box"></p>
</body>
</html>

box-shadow Attributes

Value Description
Default value. No shadow is
none
displayed
Required. The position of the
h-
horizontal shadow. Negative
shadow
values are allowed
Required. The position of the
v-
vertical shadow. Negative values
shadow
are allowed
blur Optional. The blur distance
Optional. The size of shadow.
spread
Negative values are allowed
Optional. The color of the shadow.
The default value is black. Look
at CSS Color Values for a
color complete list of possible color
values.
Note: In Safari (on PC) the color
parameter is required. If you do
not specify the color, the shadow
is not displayed at all.
Optional. Changes the shadow
inset from an outer shadow (outset) to
an inner shadow
Sets this property to its default
initial
value. Read about initial
Inherits this property from its
inherit
parent element. Read about inherit

Transparency

Apply the effect of transparency with the opacity property. Opacity


determines how transparent an object appears.

The syntax for applying a transparency to an image or other element


is:
opacity: value
The value for the opacity object is a number between 0.0 and 1.0.

*1.0 means that the object is entirely opaque, while 0.0 means that it
is entirely transparent.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#box {
opacity: .5;
background: #73AD21;
padding: 20px;
width: 150px;
height: 100px;
}
</style>
</head>
<body>
<p id="box"></p>
</body>
</html>

Background Gradients

A gradient is a smooth transition from one color to another.


In CSS3, you can apply gradients to a number of objects, such as
headers, footers, buttons, and more.

Gradients are applied through the background property with one of


the methods:
- linear-gradient: Creates a gradient from top to bottom or vice versa, or
from corner to corner
- radial-gradient: Creates a gradient that radiates out from a central point
- repeating-linear-gradient: Creates a repeating linear gradient, which
results in straight bands of gradient color
- repeating-radial-gradient: Creates a repeating radial gradient, which
results in circular bands of gradient color

Linear Gradients
To create a linear gradient, you must define at least two-color stops.
Color stops are the colors you want to render smooth transitions among. You
can also set a starting point and a direction (or an angle) along with the
gradient effect.

Syntax:
background: linear-gradient(direction, color stop1, color-stop2, ...);
<!DOCTYPE html>
<html>
<head>
<style>
#box {
background: linear-gradient(to right, purple, #3D5266, red, green);
padding: 20px;
width: 150px;
height: 100px;
}
</style>
</head>
<body>
<p id="box"></p>
</body>
</html>

Radial Gradients
A radial gradient is defined by its center. To create a radial gradient,
you must also define at least two color stops.

Syntax
background: radial-gradient(shape size at position, start-color, ..., last-
color);
By default, shape is ellipse, size is farthest-corner, and position is
center.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#box {
background: radial-gradient(circle, red, yellow, green);
padding: 20px;
width: 150px;
height: 100px;
}
</style>
</head>
<body>
<p id="box"></p>
</body>
</html>
Transformations
In HTML5/CSS3, you can now transform 2D and 3D objects.

A transform is an effect that lets you change the size, shape, and
position of an element. This includes rotating, scaling, stretching, spinning
and moving elements.
To add transformations, use the transform property with one of its
methods.
2D Translations
A translation moves an element without rotating, skewing, or turning
the image.

To translate an object, use the transform property in combination


with the translate() method.

The translate() method accepts two values: one to adjust its position
on the x-axis and another on the y-axis.
transform: translate(100px,50px);
2D Scaling
Scaling an element will increase or decrease its size. To scale an
object, use the transform property in combination with the scale() method.

The scale() method accepts two values: a factor to adjust its width and
another to adjust its height.
transform: scale(2,4);
2D Rotation
Rotating an element will turn it clockwise or counterclockwise. To
rotate an object, use the transform property in combination with the rotate()
method.

The rotate() method accepts one value: the number of degrees to


rotate the object.
transform: rotate(30deg);
3D Rotation
3D rotation will rotate an element around its x-axis or y-axis. To 3D
rotate an object, use the transform property in combination with the rotateX()
or rotateY() methods.

The rotateX() and rotateY() methods accepts one value: the number of
degrees to rotate the object around an axis.
transform: rotateX(180deg);
2D and 3D Skewing
Skewing an element will stretch it one or more directions. To skew an
object, use the transform property in combination with the skew() method.

The skew() method accepts two values: the number of degrees to turn
the object around the x-axis and another for the y-axis
transform: skewX(45deg);
3D perspective
Perspective, in terms of drawings and illustrations, is the
convergence of lines that give the
illusion of depth. The CSS3 3D perspective property defines how a browser
renders the depth of a 3D transformed element. The perspective property
takes on a number value: lower values (in the range of 1 to 1000) create a
more pronounced effect than higher values.
perspective: number;

<!doctype html>
<html>
<head>
<title></title>
<style type="text/css">
div {
padding: 40px 40px;
background: #B8860B;
width: 150px;
color: #fff;
font-family: sans-serif;
font-size: xx-large;
}

div#div2 {
margin: 100px;
perspective: 600;
margin: 100px 0 0 50px;
-ms-perspective: 600;
margin: 100px 0 0 50px;
-moz-perspective: 600;
margin: 100px 0 0 50px;
-o-perspective: 600;
margin: 100px 0 0 50px;
-webkit-perspective: 600;
margin: 100px 0 0 50px;
transform: rotate3d(0, 1, 1, 45deg);
-ms-transform: rotate3d(0, 1, 1, 45deg);
-moz-transform: rotate3d(0, 1, 1, 45deg);
-o-transform: rotate3d(0, 1, 1, 45deg);
-webkit-transform: rotate3d(0, 1, 1, 45deg);
}
</style>
</head>
<body>
<div>Original element</div>
<div id="div2">Transformed element</div>
</body>
</html>

Transitions

In CSS3, a transition is a visible movement from one state to another


on screen. To create a transition, use the transition property.
Set the value as the property that you would like to change. You must
also set the duration, the delay, and the timing function.

This can be done with the transition property or by using specific


properties for each.

<!doctype html>
<html>
<head>
<title></title>
<style type="text/css">
#wrapper {
transition-property: opacity;
transition-duration: 3s;
transition-delay: 1s;
transition-timing-function: linear;
}

#wrapper #before, #wrapper:hover #after {


opacity: 1;
}

#wrapper:hover #before, #wrapper #after {


opacity: 0;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="before">Now you see me</div>
<div id="after">Now you don't</div>
</div>
</body>
</html>
Animations
Animations move static images in a way that makes them appear as
though they are moving.

Unlike transitions, animations use the @keyframes rule, which


allows you to adjust the timings of an animation.
You can dictate when an action occurs by using a percent. i.e. 50% of
the way through this animation, the element should be yellow.
<!doctype html>
<html>
<head>
<title></title>
<style type="text/css">
div {
width: 200px;
height: 200px;
background: limegreen;
animation: a1 3s;
}

@keyframes a1 {
from {
background: limegreen;
}

to {
background: dodgerblue;
}
}
</style>
</head>
<body>
<div></div>
</body>
</html>
19 - Building Interactive Applications
HTML5 and CSS3 are awesome for creating beautiful websites.
However, todays users want an interactive Web experience.

Interactivity allows a user to take an action and receive a response.


Implementing interactivity requires a programming language, such as
JavaScript.

JavaScript is a loosely-typed scripting language that is interpreted by


a browser. It changes how elements in an HTML document act and respond
to user input.

We create scripts with JavaScript. Scripts are step-by-step


instructions that tell a browser how to respond to events, such as a user
clicking a button. The file extension for a script is .js .
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>My First JavaScript</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.
</button>
<p id="demo"></p>
</body>
</html>
If the JavaScript program doesnt display, you need to enable
JavaScript in your Web browsers preference settings. In Internet Explorer 9,
for example, select Tools > Internet options. In the Internet Options dialog
box, click the Security tab. Click the Custom level or Default level button,
whichever is available. In the Security Settings dialog box, scroll down to the
Scripting. Click the Enable radio button under Active scripting, and then
click OK twice to close the dialog boxes. Try opening the file again in your
Web browser to run the JavaScript program.
What JavaScript can do
1. JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().

This example uses the method to "find" an HTML element (with


id="demo") and changes the element content (innerHTML) to "Hello
JavaScript":
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>
JavaScript accepts both double and single quotes!
2. JavaScript Can Change HTML Attributes
This example changes an HTML image by changing the src (source)
attribute of an <img> tag:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attributes.</p>
<p>In this case JavaScript changes the src (source) attribute of an image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the
light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the
light</button>
</body>
</html>
3. JavaScript Can Change HTML Styles (CSS)
Changing the style of an HTML element, is a variant of changing an
HTML attribute:
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click
Me!</button>
</body>
</html>
4. JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!
</button>
</body>
</html>

5. JavaScript Can Show HTML Elements


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button type="button" onclick="document.getElementById('demo').style.display='block'">Click
Me!</button>
</body>
</html>
We can connect JavaScript to HTML documents in a couple of ways:
- Embedding it with the <script> tag
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
- Linking a separate JavaScript file to the HTML document
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="myScript.js"></script>
</head>
<body>
</body>
</html>
20 - Creating and Using Functions and
Variables in JavaScript
A function is a group of statements that are combined to perform a
specific task.

A statement is a line of code that performs an action. Statements


should end with a semicolon (;).

If different parts of a script repeat the same task, then you can reuse a
function instead of repeating the same statements.

A JavaScript function is executed when "something" invokes it (calls


it).

A JavaScript function is defined with the function keyword, followed


by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...).

The code to be executed, by the function, is placed inside curly


brackets: {}

Function parameters are the names listed in the function definition.

Function arguments are the real values received by the function


when it is invoked.
Inside the function, the arguments (the parameters) behave as local
variables.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function HelloWorld() {
alert("Hello World!");
}
</script>
</head>
<body>
<a href="javascript:HelloWorld()">Hello</a>
</body>
</html>
Definition and Execution of Functions
The way that a function is defined is different from how it is executed
by a browser.

A functions definition outlines its name, any parameters it may take,


and its statements.
NOTE: a definition doesnt perform any of a functions statements.
The code inside the function will execute when "something" invokes (calls)
the function:
- When an event occurs (when a user clicks a button)
- When it is invoked (called) from JavaScript code Automatically (self
invoked)

When JavaScript reaches a return statement, the function will stop


executing.
If the function was invoked from a statement, JavaScript will "return"
to execute the code after the invoking statement.
Functions often compute a return value. The return value is
"returned" back to the "caller":
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>

Variables
Scripts should temporarily store pieces of information. These bits of
data can be stored as variables.

Its called a variable because its values can vary every time a program
is run. Variables can be defined using the var syntax with a unique keyword,
such as height or width.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables</p>
<p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
</body>
</html>

All JavaScript variables must be identified with unique names.


These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
The general rules for constructing names for variables (unique
identifiers) are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letter
- Names can also begin with $ and _ (but we will not use it in this tutorial)
- Names are case sensitive (y and Y are different variables)
- Reserved words (like JavaScript keywords) cannot be used as names
- JavaScript identifiers are case-sensitive.

Types of Data

- Numbers 1, 2, 3
var length = 16;
- Strings Zombies freak me out!
Must always be surrounded by quote marks
var lastName = "Johnson";
- Boolean true, false
var x = true; var y = false;
- Objects
var x = { firstName:"John", lastName:"Doe" };
- Arrays
var cars = ["Saab", "Volvo", "BMW"];

Comments
Add comments to your script to explain what it does. It will also make
your code easier for others to read and understand.

Add a single-line comment by placing two forward slash characters //


in front of your comment. Anything after the slashes wont be interpreted by
the browser.
Add a multi-line comment by starting with the /* characters and
ending with the */ characters. Anything between these characters wont be
interpreted by the browser.
/*These comments are typically reserved for describing how an entire script file works or to comment
out an entire block of script. */

//this function does something awesome!


function doSomethingAwesome() {
var name = prompt(What is your name?);
alert(name + , you just did something awesome!");
}
21 - jQuery and Other Third-Party
Libraries
JavaScript Libraries

The most effective programmers know how to make good use of what
others write. A programming library contains snippets of code, subroutines,
classes, and other resources you can re-use to create software. There are
many JavaScript libraries available, and jQuery is one of the most popular.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>First use of jQuery</title>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js"></script>
<script type="text/javascript">
//Once the HTML document loads, execute the function within ready().
$(document).ready(function () {
//Each paragraph receives a "click" action, hide that particular paragraph.
$("p").click(function () {
$(this).hide();
});
});
</script>
</head>
<body>
<p>
This is the first paragraph. Click on me to make me
disappear.
<p>This is the second paragraph.
<p>This is the third paragraph.
</body>
</html>
22 - Objects in JavaScript
An HTML element is an object, like a house or a car. Just as with real
life objects, we can access and modify HTML objects that appear on a screen.
The creation of interactive Web pages and apps relies on our ability to
manipulate objects on a screen. Objects are models of things in the real
world that were built using data. Objects are grouped into object models,
which are used to represent Browsers and Web pages.

In JavaScript, almost "everything" is an object.


- Booleans can be objects (if defined with the new keyword)
- Numbers can be objects (if defined with the new keyword)
- Strings can be objects (if defined with the new keyword)
- Dates are always objects
- Maths are always objects
- Regular expressions are always objects
- Arrays are always objects
- Functions are always objects
- Objects are always objects

All JavaScript values, except primitives, are objects.


JavaScript Primitives

A primitive value is a value that has no properties or methods.

A primitive data type is data that has a primitive value.

JavaScript defines 5 types of primitive data types:


- string
- number
- boolean
- null
- undefined
Primitive values are immutable (they are hardcoded and therefore
cannot be changed).
Value Type Comment
"Hello" string "Hello" is always "Hello"
mar.14 number 3.14 is always 3.14
TRUE boolean true is always true
FALSE boolean false is always false
null
null null is always null
(object)
undefined undefined undefined is always undefined

With JavaScript, you can define and create your own objects.

There are different ways to create new objects:


- Define and create a single object, using an object literal.
- Define and create a single object, with the keyword new.
- Define an object constructor, and then create objects of the constructed type.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>
</body>
</html>
23 - Document Object Model (DOM)
When a web page is loaded, the browser creates a Document Object
Model of the page.
TheHTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
- JavaScript can change all the HTML elements in the page
- JavaScript can change all the HTML attributes in the page
- JavaScript can change all the CSS styles in the page
- JavaScript can remove existing HTML elements and attributes
- JavaScript can add new HTML elements and attributes
- JavaScript can react to all existing HTML events in the page
- JavaScript can create new HTML events in the page

The HTML DOM is a standard object model and programming


interface for HTML. It defines:
- The HTML elements as objects
- The properties of all HTML elements
- The methods to access all HTML elements
- The events for all HTML elements

In other words: The HTML DOM is a standard for how to get,


change, add, or delete HTML elements.
24 - Locating and Accessing Elements
We can access objects in the DOM using an elements ID.
To do so, we can use the document objects getElementById()
method. This means that the element must have an ID. Using this method
allows you to manipulate the contents of that element.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
Other methods
- Finding elements by id
- Finding elements by tag name
- Finding elements by class name
- Finding elements by CSS selectors
- Finding elements by HTML object collections
25 - Listening and Responding to Events
Events in Programming

Events are actions that a user takes. JavaScript features event


handlers, which respond to specific user events.
For example, the onClick event handler responds to clicks on screen.
Event handlers respond by executing functions.

Examples of HTML events:


- When a user clicks the mouse
- When a web page has loaded
- When an image has been loaded
- When the mouse moves over an element
- When an input field is changed
- When an HTML form is submitted
- When a user strokes a key

onsubmit form submission


onkeydown
onkeypress keystrokes
onkeyup
onclick
mouse or touchpad
onmousedown
clicks
onmouseup
onload
page loading/unloading
onunload
onselect item selection
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Select some of the text:<input type="text" value="Hello, World!" onselect="myFunction()">
</p>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById('demo').innerHTML = "Selecting text is awesome!";
}
</script>
</body>
</html>
26 - Changing, Adding and Deleting
Elements
Updating Content in Elements

Use the innerHTML property to change content or insert new


content between element tags. It can be used on any element. To change
content, set the innerHTML property to the desired string. To do this, we
must use the equals symbol (=). To remove content, set it to an empty string.
element.innerHTML = new Change the inner
html content HTML of an element
Change the attribute
element.attribute = new value value of an HTML
element
Change the attribute
element.setAttribute(attribute,
value of an HTML
value)
element
element.style.property = new Change the style of
style an HTML element

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="demo" onclick="myFunction()">Click me</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Using JavaScript is super fun!";
}
</script>
</body>
</html>
Adding and Deleting Elements

Make elements, like images, appear on screen with the document


objects createElement method. Add the element to the screen using the
appendChild() method.
Create an HTML
document.createElement(element)
element
Remove an HTML
document.removeChild(element)
element
Add an HTML
document.appendChild(element)
element
Replace an HTML
document.replaceChild(element)
element

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="demo"></p>
<button onclick="show_image ('cat.jpg',200,150,'cats');">
Display an image!
</button>
<script>
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
document.body.appendChild(img);
}
</script>
</body>
</html>
27 - Coding Animations by Using
JavaScript
Animation is the modification of static images to create the effect of
movement. Animation can be used to dynamically move objects in the user
interface. We can leverage JavaScript to create powerful animations.
To demonstrate how to create HTML animations with JavaScript, we
will use a simple web page.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>My First JavaScript Animation</h2>
<div id="animate">My animation will go here</div>
</body>
</html>

All animations should be relative to a container element.


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>My First JavaScript Animation</h2>
<div id="container">
<div id="animate">My animation will go here</div>
</div>
</body>
</html>

The container element should be created with style = "position:


relative".
The animation element should be created with style = "position:
absolute".
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
</head>
<body>
<h2>My First JavaScript Animation</h2>
<div id="container">
<div id="animate">My animation will go here</div>
</div>
</body>
</html>
JavaScript animations are done by programming gradual changes in
an element's style.
The changes are called by a timer. When the timer interval is small,
the animation looks continuous.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id="container">
<div id="animate"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
28 - Working with Images, Shapes, and
Other Graphics
JavaScript can display different types of graphics, from JPG and PNG
files to shapes like
boxes and circles. One method is to use the createElement() method as shown in
chapter 26.
Manipulating the Canvas with JavaScript

Recall that the canvas element is used to create a container for


graphics.
With JavaScript, you can manipulate the container and draw graphics
dynamically.

To draw a canvas object, you use the getElementById() function to


access the canvas and the canvas.getContext to create the object.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="myCanvas" width="400" height="100" style="border:3px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "Blue";
ctx.fillRect(5, 5, 150, 75);
</script>
</body>
</html>
29 - Transmitting Data
Creating robust interactive applications requires the ability to send
and receive data.
For this to happen, mobile applications and HTML Web pages have
to communicate with servers where data is stored.

A users computer is commonly called a client.

JavaScript makes the creation of such programs possible.

One of the most essential techniques for data transfer involves the
XMLHttpRequest API (sometimes abbreviated as XHR).
XMLHttpRequest enables you to use JavaScript to pass data in the form of
text strings between a client and a server. The general syntax might look like
the following:
function load(url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function () {
callback(xhr.responseText);
}
xhr.send(data);
}

The XMLHttpRequest object creates a call to the server. The open


method specifies the HTTP method for contacting the server and provides the
servers Web address. The callback function gets a response from the server.
Finally, xhr.send(data) sends the data.
<!doctype html>
<html>
<head>
<title>JavaScript accesses data</title>
<script type="text/javascript">
function init() {
var paragraph_object =
document.getElementById('paragraph');
message = "Notice that the title of this page is'" + document.title + "'.";
paragraph_object.innerHTML = message;
}
</script>
</head>
<body onload="init();">
<h1>JavaScript accesses data</h1>
<p id="paragraph"></p>
</body>
</html>

In real-world programming, JavaScript can handle highly complicated


operations. One might, for instance, receive an involved report on gasoline
prices at a long list of retail outlets and need the ability to isolate just one of
those figures.

Parsing is a term used to describe analysis of complex information


into constituent parts.
<!doctype html>
<html>
<head>
<title>Parsing complex data</title>
<script type="text/javascript">
// The next statement needs to appear on a single line.
sample_data = "Mobil-17: 3.49; Kroger-03: 3.36; Exxon-01: 3.59; Kroger-04: 3.49; Valero-A:
3.41; Chevron-01: 3.52";
of_interest = "Kroger-04";
function init() {
var paragraph_object =
document.getElementById("paragraph");
var data_list = sample_data.split(';');
for (j = 0; j < data_list.length; j++) {
parts = data_list[j].split(':');
var site = parts[0].trim()
if (site == of_interest) {
var message = "Given the sample data '" + sample_data + "', this program parsed out the
price $" + parts[1].trim() + " for the " + site + " site.";
paragraph_object.innerHTML = message;
}
}
}
</script>
</head>
<body onload="init();">
<h1>Parsing complex data</h1>
<p id="paragraph">Welcome.</p>
</body>
</html>

JavaScript and freely available JavaScript libraries supply a wealth of


parsing facilities.

Extraction of data from a human-readable external Web page is only


one instance among many of how JavaScript can parse data.
For example, you can also use a subset of JavaScript
called JSON (JavaScript Object Notation) to exchange JavaScript objects
with a server.
It features two APIs: JSON.parse and JSON.stringify. When data is
received from a server, the .parse API is used to read the data. When data is
sent by a client, the .stringify API is used to turn data into text strings.

JSON is built on two structures:


- A collection of name/value pairs. In various languages, this is realized as an
object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In most languages, this is realized as an array,
vector, list, or sequence.
30 - Loading and Saving Files
Validating Uploaded Files

With JavaScript you can load and save files from your computer.
JavaScript can also be used to validate a file type.

Example: Users should upload a .jpg file, but try to upload a .doc file
instead
<!doctype html>
<html>
<head>
<title>JavaScript accesses local files</title>
<script type="text/javascript">
function acknowledge(file_handle) {
var size = file_handle.size;
var fname = file_handle.name;
var message = "You have chosen the file '" +
fname + "'. This appears to be a recognizable image, totaling " + size + " bytes in size.";
alert(message);
}
function complain(fname) {
var message = "The file named '" + fname + "'does not appear to have an acceptable extension.";
alert(message);
}
function handle_file_selection(item) {
var f = item.files[0];
var fname = f.name;
var last_index = fname.lastIndexOf('.');
if (last_index == -1) {
complain(fname);
return;
}
var ext = fname.substr(last_index + 1);
if (ext.toLowerCase() in { 'gif': '', 'jpg': '', 'png': '', 'tif': '' }) {
acknowledge(f);
} else {
complain(fname);
}
}
</script>
</head>
<body>
<h1>JavaScript accesses local files</h1>
<input type='file'
onchange='handle_file_selection(this);' />
</body>
</html>

AppCache for Offline Files

Data can be stored locally when a user is offline using the


Application Cache, or AppCache.
AppCache stores resources, such as HTML, CSS, and JavaScript files,
locally on a users machine. As a result, users can access Web pages and apps
offline.

The cache manifest file dictates which type of information is stored


offline.
<!doctype html>
<html manifest="test.appcache">
<head>
<title>Minimal AppCache example</title>
</head>
<body>
<h1>Minimal AppCache example</h1>
<p>This page should reload after disconnecting from the Internet and refreshing the Web page. </p>
</body>
</html>
Validating User Input
Form input may be incorrect.

Example: Users may forget the @ symbol in an email address.


JavaScript can be used to perform client-side validation of form input.
This occurs in the browser before a form is submitted.

NOTE: With HTML5, client-side validation is performed based on the input


type
<!doctype html>
<html>
<head>
<title>Form management</title>
<script type="text/javascript">
function correct() {
var input_object =
document.getElementById("serial");
var value = input_object.value;
var current_length = value.length;
if (current_length) {
var last_character =
value.substring(current_length - 1);
switch (current_length) {
case 4:
case 8:
case 11:
if (last_character != '-') {
value = value.substring(0,
current_length - 1);
}
break;
default:
if (!/\d/.test(last_character)) {
value = value.substring(0,
current_length - 1);
}
}
if (current_length > 12) {
value = value.substring(0, current_length
- 1);
}
current_length = value.length;
switch (current_length) {
case 3:
case 7:
case 10:
value += "-";
}
input_object.value = value;
}
}
</script>
</head>
<body>
<h1>Form management</h1>
<form>
Enter here a serial number in the pattern XXX-XXX-XXX, where each X is a digit: <input
id="serial" type='text' size='12' onkeyup="correct();">.
</form>
</body>
</html>
Cookies
Cookies are small text files that that Web sites save on your computer.
They contain information about you and your preferences. With JavaScript
you can store and retrieve information from cookies.
<!doctype html>
<html>
<head>
<title>Use of cookies</title>
<script type="text/javascript">
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function init() {
var message;
level_object = document.getElementById("level");
var welcome = document.getElementById("welcome");
var level = getCookie("level");
if (level == null || level == '') {
message = "It appears this is your first time to play. You will start at level 1.";
level = 1;
} else {
message = "When you last played, you reached level " + level + ". You will start there now.";
}
welcome.innerHTML = message;
level_object.value = level;
}
function save_level() {
setCookie("level", level_object.value, 10);
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
</script>
</head>
<body onload="init();">
<h1>Use of cookies</h1>
<p id="welcome">Welcome.</p>
<form>
You can update your level at any time. It is currently set at <input id="level" type="number"
min="1" max="100" oninput="save_level();" />.
</form>
</body>
</html>

Local Storage

Cookies are limited in the information they store, and therefore in the
effects programming with them can achieve. Plus, cookies pose a threat to
data privacy. HTML5 provides local storage to make personalization easier
to program and more capable.
<!doctype html>
<html>
<head>
<title>Use of local storage</title>
<script type="text/javascript">
function init() {
var message;
level_object = document.getElementById("level");
var welcome = document.getElementById("welcome");
var level = localStorage.level;
if (level == null || level == '') {
message = "It appears this is your first time to play. You will start at level 1."; level = 1;
} else {
message = "When you last played, you reached level " + level + ". You will start there now.";
}
welcome.innerHTML = message;
level_object.value = level;
}
function save_level() {
localStorage.level = level_object.value;
}
</script>
</head>
<body onload="init();">
<h1>Use of local storage</h1>
<p id="welcome">Welcome.</p>
<form>
You can update your level at any time. It is currently set at <input id="level" type="number"
min="1" max="100" oninput="save_level();" />.
</form>
</body>
</html>
31 - Responding to the Touch Interface
Devices with touch interfaces have screens that are developed
specifically for sensing touch. There are two different types of touch screens:
- Capacitive touch screens
- Resistive touch screens

Processors treat touches like mouse gestures and relay that


information to the operating system and application.

Returning at chapter 6 we recall finger moves are called gestures, and


can include a press, tap, slide, and more. How an application responds to a
gesture is called a touch event.
We can use JavaScript, including the touchstart, touchend, and
touchmove methods to create touch events.
Tap Left-click
Tap a finger on You use the
the screen addEventListener
Left Tapping a method to attach an event
Double tap double- finger on the handler to an HTML
click screen twice element, which can be a
Press and hold div, link, or anything you
Right- a finger on the want. Using
Press and hold
click screen, then addEventListener lets
release you do something useful
Mouse Drag a finger when an event is
Selection/drag drag to the left or triggered.
(selection) right
CTRL +
mouse Pinch an object
Zoom wheel inwards or
forward or outwards
backwards

Gesture events are triggered for multi-finger gestures. The main


gesture events are:
- gesturestart: Every new two-finger gesture triggers a gesturestart event.
- gesturechange: When both fingers move around the screen, a gesturechange
event occurs.
- gestureend: Lifting both fingers from the screen triggers a gestureend event.

The action an application takes in response to a gesture is called a


touch event. You can use JavaScript to create touch events in touch-enabled
apps. Developers can draw from a large set of input application programming
interfaces (APIs) that work with touch screen data.

The primary JavaScript touch events are:


touchstart: Every new finger touch triggers a touchstart event.
touchmove: When a finger moves around the surface of the screen, a
touchmove event occurs, which tracks the finger movement.
touchend: Lifting the finger from the screen triggers a touchend event.
touchcancel: The touchcancel event is triggered when the device launches
another application.

In JavaScript, the touch object detects input from touch-enabled


devices. You reference touch objects in the touchlist, which includes all of
the points of contact with a touch screen.

A single tap has one entry in the touchlist, whereas a three-finger


gesture would have a total of three entries. Touch objects are read-only and
have the following properties:
- identifier: A unique identifier for the touch
- target: The HTML element that the touch affected
- clientx: Horizontal position, relative to browser window
- clienty: Vertical position, relative to browser window
- pagex: Horizontal position, relative to HTML document
- pagex: Vertical position, relative to HTML document
- screenx: Horizontal position, relative to the screen
- screeny: Vertical position, relative to the screen
- rotation: Indicates the amount of two-finger rotation that occurred. The
value of the rotation is in degrees; positive values are clockwise, and negative
values are counterclockwise.
Each touch event includes three different touchlists:
- touches: A list of all touch points currently in contact with the screen
- targetTouches: A list of touch points currently in contact with the screen
and whose touchstart event occurred within the same node (inside the same
target element as the current target element)
- changedTouches: A list of touch points that caused the current event to be
fired; for example, in a touchend event, this is the finger that was removed

Detecting a Touch Screen


<!doctype html>
<html>
<head>
<title>Detect Touch Screen</title>
<meta charset="utf-8" />
<style type="text/css">
#canvas {
background-color: grey;
}
</style>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", init, false);
function init() {
var canvas = document.getElementById("canvas");
if ("ontouchstart" in document.documentElement) {
canvas.addEventListener("touchstart", detect, false);
}
else {
canvas.addEventListener("mousedown", detect, false);
}
}
function detect() {
if ("ontouchstart" in document.documentElement) {
alert("Touch screen device detected!");
}
else {
alert("No touch screen device detected.");
}
}
</script>
</head>
<body>
<canvas id="canvas" width="50" height="50"></canvas>
<br />
<p>Click the box to start touch screen detection.</p>
</body>
</html>
32 - Coding Additional HTML5 APIs
WHATWG is a consortium that was formed by Apple, the Mozilla
Foundation, and Opera Software to define and document HTML5.

This organization is different from W3C. The WHATWG HTML5


specification includes the following additional APIs in its HTML5
specification:
- Geolocation
- Web Workers
- WebSockets
- File

Geolocation
The HTML Geolocation API is used to get the geographical position
of a user.

Since this can compromise privacy, the position is not available


unless the user approves it.
The getCurrentPosition() method is used to return the user's
position.

The example below returns the latitude and longitude of the user's
position:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " +
position.coords.longitude;
}
</script>
</body>
</html>
Web Workers

A web worker is a JavaScript running in the background, without


affecting the performance of the page.
<!DOCTYPE html>
<html>
<head>
<title>Big for loop</title>
<script>
var worker = new Worker('doWork.js');
worker.onmessage = function (event) {
alert("Completed " + event.data + "iterations");
};
function sayHello() {
alert("Hello sir....");
}
</script>
</head>
<body>
<input type="button" onclick="sayHello();" value="Say Hello" />
</body>
</html>

doWork.js
onmessage = function (event) {
var info = event.data;
var result = 'Hello ' + info + ' everywhere';
postMessage(result);
};
WebSocket API
The WebSocket API creates a simultaneous two-way connection
between a client and a Web server. This type of connection is called a socket,
and it allows data to flow back and forth freely.
WebSockets are commonly used for real-time applications like chat,
multiplayer online gaming, or sports score tickers.
There are three primary events that occur with WebSocket
communication:
- onopen: when a socket opens
- onmessage: when a message is received from a Web server
- onclose: when a socket closes

A WebSocket that tests whether your browser supports WebSockets:


<!doctype html>
<html>
<head>
<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("Your browser supports WebSockets.");
// Open a WebSocket
var socket = new
WebSocket("ws://localhost:9998/echo");
socket.onopen = function () {
// Connected, send data
socket.send("Connected"); alert("Connected.");
};
socket.onmessage = function (e) {
var received_msg = e.data;
alert("Message received.");
};
socket.onclose = function () {
// WebSocket closed
alert("Connection closed.");
};
}
else {
// Browser doesn't support WebSockets
alert("Your browser does not support WebSockets.");
}
}
</script>
</head>
<body>
<div>
<a href="javascript:WebSocketTest()">
Click to run
WebSocket demo
</a>
</div>
</body>
</html>

A second alert box should appear, stating that the connection is


closed.

File API

The File API allows Web applications to upload files from local
storage to remote servers.
The File API features several interfaces for accessing files, including:
- File: reads in a file as a URL
- FileList: permits upload of multiple files or a folder of files
- Blob: provides access to raw binary data
- FileReader: Provides methods to read and display a file
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>File API Browser Support Check</title>
<script>
if (window.File && window.FileReader && window.FileList &&
window.Blob) {
alert('Hurray! This browser supports File APIs.');
} else {
alert('This browser does not fully support File APIs.');
}
</script>
</head>
<body>
</body>
</html>
33 - Accessing Device and Operating System
Resources
The Windows Runtime environment enables developers to access in-
memory resources as well as hardware using APIs.
As you learned in chapter 4, the Windows Runtime (WinRT) is the
operating system environment responsible for access to devices, media,
networking, local and remote storage, and other items.

The Web Storage API allows you to store data in the browser versus
a server.

There are two different types of storage:


- localStorage - lets users save larger amounts of persistent data, there is no
limit to how long the data persists.
- sessionStorage lets users save session state data, it only lasts for the duration
of the session.
Both objects allow users to store large amounts of data without
slowing down a connection because data is transferred only when requested.

localStorage
<!doctype html>
<html>
<head>
<title>localStorage Example</title>
<script type="text/javascript">
function load() {
var value = localStorage.getItem("myKey");
if (!value) {
alert("Item not found, adding to localStorage");
localStorage.setItem("myKey", "myValue");
}
else {
alert(value + " found!");
}
}
</script>
</head>
<body onload="load()">
</body>
</html>

Refresh or Reopen the file

sessionStorage

Changing each instance of localStorage to sessionStorage.


<!doctype html>
<html>
<head>
<title>localStorage Example</title>
<script type="text/javascript">
function load() {
var value = sessionStorage.getItem("myKey");
if (!value) {
alert("Item not found, adding to sessionStorage.");
sessionStorage.setItem("myKey", "myValue");
}
else {
alert(value + " found!");
}
}
</script>
</head>
<body onload="load()">
</body>
</html>

Refresh Page:
Close page and reopen:

Accessing Hardware Capabilities


Building with HTML5, CSS, and JavaScript leads to device-
independent apps. Device-independent apps are able to access hardware
capabilities, such as:
- Global Positioning System (GPS)
- Accelerometer
- Camera
34 - Bootstrap
Responsive web design is about creating web sites which
automatically adjust themselves to look good on all devices, from small
phones to large desktops.

Bootstrap is a free front-end framework for faster and easier web


development.
Bootstrap includes HTML and CSS based design templates for
typography, forms, buttons, tables, navigation, modals, image carousels and
many other, as well as optional JavaScript plugins.

Bootstrap also gives you the ability to easily create responsive


designs.

There are two ways to start using Bootstrap on your own web site.
Downloading Bootstrap

If you want to download and host Bootstrap yourself, go to


getbootstrap.com, and follow the instructions there.
Bootstrap CDN

If you don't want to download and host Bootstrap yourself, you can
include it from a CDN (Content Delivery Network).
MaxCDN provides CDN support for Bootstrap's CSS and JavaScript.
You must also include jQuery.
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->


<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Bootstrap 3 is designed to be responsive to mobile devices. Mobile-


first styles are part of the core framework.

To ensure proper rendering and touch zooming, add the following


<meta> tag inside the <head> element:
<meta name="viewport" content="width=device-width, initial-
scale=1">

The width=device-width part sets the width of the page to follow the
screen-width of the device (which will vary depending on the device).

The initial-scale=1 part sets the initial zoom level when the page is
first loaded by the browser.
Bootstrap also requires a containing element to wrap site contents.

The .container class provides a responsive fixed width container


The .container-fluid class provides a full width container, spanning
the entire width of the viewport

In the next chapter, you will see how we will use bootstrap in our
application.
35 Weather application development
Lets create an application that will show the weather at the user's
current location.
There are 2 keywords here, weather and local. To get the
geographical position of a user we will use a free lookup API, to quickly and
simply integrate IP geolocation into our script. For the weather will use a
weather API.
Type on Google weather api and click on the first link.

This is a free weather API that we will use on our application.


https://openweathermap.org/api

As we are interested to show on our application the current weather,


click on the first option.
On the right at the page we can see, that we can access the current
weather data of one location, after geographic coordinates.

If we open the example provided we can see the url and the arguments
that will be read by the api server when we will call it.

As we see, we will need the latitude, longitude and another argument


called appid.

As we will use https://openweathermap.org/api for our weather app,


in order to access the API freely we need to sign up for an API key, as they
are sayng on their documentation. This API key is in fact the appid
argument.
In the API keys tab you will find your unique key for this API.

Let's build a container for our application first.

Lets create in the same location a index.html file and a css file, for
which we will include a reference in the head of our html file.
Because we want our application to be dynamic and responsive we
will use Bootstrap including it from a CDN.

In the body,we will create a container for our app with the <div
id="container-fluid"></div> so we can add some style to it.
Lets add a background to the page. Im using a free pattern that I
downloaded from google, and lets style the container.

We have now a basic responsive container for our application.


We will use javascript to build our app, so we will create an external
javascript file, in the same location with the name javascript.js that we will
insert in our container with:
<script src="javascript.js"></script>

First we will get the geographic coordinates of the user. Since all this
will be inside jQuery we will start by declaring a function inside a jQuery
wrapper, so this will execute when the document is ready.
$(function () {

// jQuery methods go here...

});

Inside this function we are going to use the http://ipinfo.io/ ,where on


Developers tab, we have a section for jQuery, to get the users geolocation.

If we run our app in the browser, on the Inspect element console, we


can see the application is retrieving our location.
Now that we have that call all set, the data logged, we want to take
this outside of the call function. Remember that this beeing inside of a call
back, data variable isnt available.
Lets declare a variable outside of the getJSON. Delete the console
log, change the parameter to d, and assign that data we get to a larger data
variable.

We need to change the lat to an actual latitude and the lon to an actual
longitude. We can do that manually.

Lets test the API key. From the example provided on the current call
weather data for one location by geographic coordinates, we can see the form
of the url to call the api.

api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid=
{apikey}
Lets replace the lat, lon and the appid, each one of you with his own
current location coordinates, and his own API key.

I am replacing the coordinates with my curent location Iasi latitude


47.151726 and longitude 27.587914 and my API default key.
lat=47.151726&lon=27.587914&appid=xxxxxxxxxxxxxxxxxxxxxxxxx
!Note: make sure to take in copy the url and open it in a new tab

In my case:
http://api.openweathermap.org/data/2.5/weather?
lat=47.151726&lon=27.587914&appid=xxxxxxxxxxxxxxxxxxxx

We can see the data that we can use for our app. Now we need to wire
this url in our script.

Lets create a variable outside of the function for our API key called
var API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

Use the key each one of you has on his account.


Lets make now the call to the weather api using a $.getJSON(). Inside of
the parenthesis we will put the url till before our unique key, where will need
to change the values for lat, lon and appid.

As the location returns from the ipinfo.io as a string with to values,


lets split the string at the comma (,), that will make it an array with the exact
values that we need.

Now we can modify in the url, the values for lat with loc[0] (the first
element of the array we just created by splitting the location string ), for
lonwith loc[1] (the second element of the array) and for the appid our
API_KEY variable .
Now that we have this call, lets add our function, lets call it wd from
weather data, and get it with a console.log.

We can see in the console we have now a bunch of data we can use.

Lets say we want to display the current location, the current weather
description, the temperature and a nice icon to reflect the weather. Lets
create some variables for that.

For the var currentLocation = wd.name; we can see what value to give from
the data in the console.
For example for the location the data is name, so will give for
currentLocation variable equal to wd our function .name
Same logic for :
var currentWeather = wd.weather[0].description;

We have an array from the first element, the description.

For the temperature we will use var currentTemp = wd.main.temp;

And for the icon, from the weather array, the first element: the icon
data.
var icon = wd.weather[0].icon;
So now we have in our script:

Lets go now on the html file. Lets say we want to display in our
container, first, the location. So,we will add a <h1 id="currentLocation">Getting
location...</h1>

Lets select the id currentLocation and update the html in our script
using $('#currentLocation').html(currentLocation);
So now we have on our app the location:

We will do the same for the temperature and the weater description.
Lets create <h2 id="currentTemp"></h2> <p id="currentWeather"></p>
Then sellect them and update the html in the javascript with:
$('#currentTemp').html(currentTemp) and $('#currentWeather').html(currentWeather);
We will have now in our app almost all the informations we want.
For the icon, on the api page at http://openweathermap.org/weather-
conditions we can find how to get the icon url.

The icons images are linked to an url, so to get them, we will select
the currentTemp and prepend the html we want (in this case the icon using
the img tag).
$('#currentTemp').prepend('<img src= >');
Because we have a string as the image source we cannot put a string
within a string.Lets declare a local variable varimgSrc and give it the vale of
the url till the icon data:

Then the data name from the console + icon +

And the format ".png"


"http://openweathermap.org/img/w/" + icon + ".png"
So now this local variable will be our img source.
Now we have also an icon for our wheater app.

Finally, we want to display the temperature in Celsius degrees not


Kelvin.
Lets replace the value of variable var currentTemp with a function
called var currentTemp = toCelsius(wd.main.temp); that we will define globally. That
will return the temp data -273.15. I also added the C letter from Celsius.
Now our app is displaying all the informations we wanted.

I will style a bit more our app.


If you remember from the beginning of this book, creating an app
requires several steps:
- Planning your project
- Designing the user interface (UI)
- Updating the app manifest
- Writing the code
- Building the app
- Debugging and testing the app
- Packaging the app
- Validating the app
- Deploying the app

O big part of them we already done. Lets create now the app
manifest.

A manifest can have three distinct sections: CACHE ,


NETWORK and FALLBACK .

CACHE:
This is the default section for entries. Files listed under this header
(or immediately after the CACHE MANIFEST) will be explicitly
cached after they're downloaded for the first time.

NETWORK:
Files listed in this section may come from the network if they aren't in
the cache, otherwise the network isn't used, even if the user is online. You
can white-list specific URLs here, or simply "*", which allows all URLs.
Most sites need "*".

FALLBACK:
An optional section specifying fallback pages if a resource is
inaccessible. The first URI is the resource, the second is the fallback used if
the network request fails or errors. Both URIs must from the same origin as
the manifest file. You can capture specific URLs but also URL prefixes.
"images/large/" will capture failures from URLs such as
"images/large/whatever/img.jpg".
We will create a new file in the same location called mysite.appcache and
will put in the html tag the manifest="mysite.appcache"

On the file we just created we will put:


CACHE MANIFEST
DATE 2017-05-17
CACHE:
NETWORK:
*
FALLBACK:
#static.html

Debugging and testing the app


Visual Studio has many tools to debug and test your app. You can
deepen more on them on you own. To debug you can use from the DEBUG
menu Other Debug Targhets, Debug Windows Phone Internet Explorer.

We can choose from different devices. On the url, type the location of
your index.html file (I uploaded all files on my website so I am using that url)

Packaging the app

To package our app, you can use http://phonegap.com/ . You can find
all instruction on how to do this on their website.

After this you will need to sign your application to be able to


distribute it on app stores. There are different ways available on google on
how to do that.
After that you will need to create a developer account on the stores
you want to publish you app.
Bibliography
https://app.pluralsight.com/library/
http://www.w3schools.com/
Microsoft Academy