Documente Academic
Documente Profesional
Documente Cultură
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
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 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.
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.
W3C provides a code validation service for all versions of HTML and
CSS at https://validator.w3.org/
Validating a Package
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.
Nesting Elements
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
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.
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 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.
<!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>
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>
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>
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
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.
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
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.).
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 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.
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
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 .
Positioning
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.
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.
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 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
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.
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
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
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>
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.
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.
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>
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
<!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>
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 W3C points out that you must declare a language using the
HTML lang or XML xml:lang attributes for correct automatic hyphenation to
occur.
or
<html xmlns=http://www.w3.org/1999/xhtml xml:lang="en" lang="en">
CSS Exclusions
Creating Shadows
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
*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
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.
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 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
<!doctype html>
<html>
<head>
<title></title>
<style type="text/css">
#wrapper {
transition-property: opacity;
transition-duration: 3s;
transition-delay: 1s;
transition-timing-function: linear;
}
@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.
If different parts of a script repeat the same task, then you can reuse a
function instead of repeating the same statements.
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>
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.
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.
With JavaScript, you can define and create your own objects.
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
<!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
<!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>
#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
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);
}
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>
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
Geolocation
The HTML Geolocation API is used to get the geographical position
of a user.
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
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
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.
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>
sessionStorage
Refresh Page:
Close page and reopen:
There are two ways to start using Bootstrap on your own web site.
Downloading Bootstrap
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">
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.
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.
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.
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.
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 () {
});
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.
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";
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;
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:
O big part of them we already done. Lets create now the app
manifest.
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"
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)
To package our app, you can use http://phonegap.com/ . You can find
all instruction on how to do this on their website.