Thursday, 30 April 2015

Html theory session 15

Document Object 
The HTML DOM provides a document object which is used within JavaScript to access all HTML elements presented on the page. The document object is one of the basic JavaScript object. It represents the entire HTML document. It provides access to other elements, such as links, anchors, and so on. 
Each HTML page has only one document object. This object is created when the BODY element is loaded on the Web page. The document object is also the part of the window object and is accessed as window.document. 
The document object provides properties that allow the user to specify or retrieve the information about the elements and its content. 



Property Description   
body Provides access to the BODY element.   
title Specifies or retrieves the title of the document.   
anchors Retrieves the collection containing all the anchors contained in a document.   
forms Retrieves the collection containing all the forms contained in a document.   
images Retrieves the collection containing all the images contained in a document.   
links Retrieves the collection containing all the links contained in a document.  
  
<!DOCTYPE html> 
<head> 
<title> Document Object </title> 
<script> 
function change_image() 

varimgText=document.getElementById(‘myImg’).alt; 
if(imgText==”ford”) 

document.getElementById(‘myImg’).src=”ferrari.jpg”; 
document.getElementById(‘myImg’).alt =”ferrari”; 
document.getElementById(‘mytext’).value =”Ferrari Car”; 

else 

document.getElementById(‘myImg’).src=”ford.jpg”; 
document.getElementById(‘myImg’).alt =”ford”; 
document.getElementById(‘mytext’).value =”Ford Car”; 


</script> 
</head>  
  
<body> 
<imgid=”myImg” src=”ford.jpg”width=”300” height=”300”alt=”ford” /><br/> 
Model: <input type=”text” id=”mytext” 
value=”Ford Car” readonly=”readonly”/><br/><br/> 
<input type=”button” value=”Change Image” onclick=”change_ image()”/> 
</body> 
</html>  

In the code, image and text elements on the page are accessed using document. getElementById() method. The method retrieves the elements based on the specified ids and sets new values for their properties. This is all done at runtime, and not through markup. The use of document.getElementById() enables to access the elements within JavaScript function and change them dynamically. 
            Figures 15.22 and 15.23 show the initial image and changed image respectively on clicking    Change Image button .
Form Object 
Form accepts input from the user and sends data for validation. JavaScript allows you to process and validate the form data. A single HTML document can contain multiple forms. The DOM specification provides a form object that represents an HTML form. A form object is created for each <form> tag in an HTML document. 
Code Snippet 16 demonstrates the use of the form object that counts number of controls in a form. 

<!DOCTYPE html> 
<head> 
<title> Form Object </title> 
<script> 
function display_length() 

var count =document.getElementById(“form1”).length; 
alert(‘Number of controls on the form: ‘ + count); 

</script> 
</head> 
<body> 
<form id=”form1” action=”welcome.php”> 
First name: <input type=”text” name=”firstname” value=”John” /><br /> 
Last name: <input ty
pe=”text” name=”lastname” value=”Smith” /><br /> 
Age : <input type=”text” name=”age” value=”40” /><br /> 
<input type=”button” value=”Controls”onClick=”display_ length()”/> 
</form> 
</body> 
</html>  

In the code, a Web page contains a form with input elements, such as text and a button. The form is accessed in JavaScript using the id attribute which is set to form1. Then, the length property of the form object is used to retrieve the number of elements in a form. 

Wednesday, 29 April 2015

html tutorials session 16

Introduction

Today, access to the Web is not limited to only desktop systems, but is also available on portable and wireless devices, such as mobiles devices. Mobile devices, such as smartphones and tablets are equipped with browsers and network access that provide a better Web experience to their users.
As the number of mobile users has increased, so has the need for a mobile Web experience that is identical to a desktop user experience. In other words, mobile users now look for applications targeting their mobiles that are similar to the ones on their desktops. This has led to the emergence of mobile Web application development.
Different companies follow distinctive strategies for developing mobile applications depending on the need of their users.
Mobile Application Environment
A mobile device, also known as a handheld device, is a small portable computing device with a small display screen and keyboard. A mobile device has an operating system on which various types of application software are executed. These application software are also known as apps. The most commonly used apps are mobile browsers that display the Web pages.
 Types of Mobile Devices
The different categories of mobile phones available in the market are as follows:
Basic mobile devices - These are very basic models with only call and Short Message Service (SMS) facility. They do not provide support for Web browsers or network access.
Low-end mobile devices - These types of models provide more features than a basic mobile device, typically Web support. There is a large market for these mobile devices and they are preferred by users who do not need heavy Internet usage. They also include a basic camera and a basic music player.
Manufacturers, such as Nokia, Motorola, Sony Ericsson, Samsung, and so forth have gained popularity for offering low cost handset in the global market.

16
Session
Building a Mobile Web Application
Concepts
V 1.1 © zetutorials Limited



Mid-end mobile devices - These types of mobile devices have gained popularity due to their increased user experience and moderate cost. Some key features of these devices include: medium sized-screen, HTML supported browser, a decent camera, games, and support for applications. They have a proprietary Operating System (OS) that is not well-known and is also not portable across various platforms.
            The mid-end mobile devices available from different manufacturers.
           High-end mobile devices - These types of mobile devices have advanced features,       such as an accelerometer, advanced camera features, and Bluetooth. They have a better look and feel as compared to mid-end mobile devices
Smartphones - These are mobile devices with multitasking capabilities. These devices have a full browser support similar to desktop browsers with wireless LAN and 3G connection. Apart from these, they have several advanced features that are as follows:
Digital Compass
Global Positioning System (GPS)
Touch screen
Camera with video recording
TV out
Bluetooth
Accelerometer
Some of the popular smartphones available in the market are Apple iPhone, a wide range of BlackBerry smartphones, HTC Magic smartphone, Nokia Lumia, Samsung Galaxy series, and so on. Concepts Session 16 Building a Mobile Web Application V 1.1 © zetutorials Limited
Figure 16.4 shows the various smartphone devices.
Figure 16.4: Smartphones
Tablets and notebooks - These devices are larger than mobile phones. They are mobile computers with a touch screen virtual keyboard and stylus or digital pen. Features of tablets include: multi-touch display, better user experience, high quality screen resolution, better Web support, and multitasking OS with high speed.
Some of the tablets available in the market are BlackBerry PlayBook Tablet PC, Samsung Galaxy Tab, and HCL Me Tab.
Figure 16.5 shows different types of tablet devices.
 Concepts Session 16 Building a Mobile Web Application V 1.1 © zetutorials Limited
16.2.2 Mobile Platforms
A mobile device platform is similar to a software platform. It is basically responsible to interact with the device hardware and run software/services on the mobile device. The mobile platforms are categorized as proprietary and open source. Proprietary platforms are those which are designed and developed by the mobile device manufacturers. These platforms are developed for specific devices and are not supported on all platforms. Open source platforms are those which are freely available to the users. The users can download the source code and alter them as per their requirements.
The brief description of the platforms available on mobile devices is as follows:
Palm OS - It is a proprietary mobile OS developed by Palm Inc. and was used for Personal Digital Assistants (PDAs). The Palm OS was later on extended to support smartphones. Currently, Palm Inc. has developed webOS, which is based on the Linux kernel. webOS is now acquired by Helwlett-Packward and is used with various devices, such as Pre, Pixi, and Veer phones as well as HP TouchPad tablet.
Blackberry OS - It is a proprietary mobile OS developed by Research in Motion (RIM) and is based on Java platform. It is primarily used by Blackberry smartphone devices.
iOS - It is a mobile OS developed by Apple Inc. and was initially referred to as iPhone OS. It is derived from Mac OS X, which is based on the UNIX platform. It was originally developed for iPhone and iPadTouch, but later extended to support other devices, such as iPad and Apple TV. iOS cannot be installed on non-Apple platforms.
Symbian - It is an open source mobile OS developed for mobile phones. It includes a user interface framework, libraries, and component tools. Symbian is the most widely supported platform for Nokia mobile devices.
Windows Mobile - It is a mobile OS that runs on top of the Windows Mobile platform.
Linux - It is an open source OS and is supported by smartphones that are manufactured by Motorola.
Android - Android is an open source OS developed by Google. It is currently used by smartphones and tablet computers. It can be customized by device manufacturers and community developers to extend the functionality of the devices.
16.2.3 Design Aspects of Mobile Web Site
The design process of a mobile Web site is similar to that of a traditional Web site developed for desktop Web browsers. Still, there are some differences between them that need to be taken into consideration.
An ideal mobile Web site is supported as well as rendered properly by maximum possible browsers and OS.
 Concepts Session 16 Building a Mobile Web Application V 1.1 © zetutorials Limited
Some of the basic considerations needed for designing a Web sites for intended mobile device are as follows:
Resolution and Physical Dimension
Page Orientation
Input methods
Resolution and Physical Dimension
The primary concern in designing a mobile Web site design is the screen resolution. The resolution means the number of pixels (width and height) on the screen of the mobile device. As there are no standards defined for screen resolution, it varies depending on its model and manufacturer.
Table 16.1 lists the resolutions of mobile devices based on their categories.

Category     Resolutions (in pixels)       
Low-end mobile devices     128 x 160 or 128 x 128       
Mid-end mobile devices     176 x 220 or 176 x 208       
High-end devices     240 x 320       
Smartphones     240 x 480, 480 × 320, 640 × 480, or 960 × 640    

webOS
Blackberry
Windows Phone
Opera Mobile
16.4 HTML5 Support on Mobiles
Today, a majority of smartphones and tablets are providing good support for HTML5. Most Android and iOS mobile devices as well as tablets use browsers that are based on Webkit. The Webkit is a layout engine supported by browsers, such as Google Chrome and Apple Safari to render Web pages.
Some of the new features introduced in HTML5 are supported by several mobile devices. This reduces the need of any third party plug-in to get those features on the mobile devices. The features suited for mobile devices are as follows:
Video
Audio
Drag and drop
Accessing browser history
Geolocation API for accessing location
Web storage API to save data on mobile devices
Offline Web applications (Applications with no Internet connection)
16.4.1 HTML5 Markup
The Web pages developed for a mobile Web application have the same structure as traditional Web pages.
A Web page contains the following sections:
Heading Structure
Document Structure Concepts Session 16 Building a Mobile Web Application V 1.1 © zetutorials Limited
16.4.2 Heading Structure
The heading structure is represented by a <head> element defined in an HTML Web page. It defines a <meta> tag that is used specifically for mobile browsers.
The brief description for some of the tags defined under <head> element is as follows:
Meta Tag
Two factors that need to be considered while designing a mobile Web application are its initial display (zoom) scale and orientation. Thus, it is necessary to inform mobile browsers to consider these factors while displaying a Web page.
This can be achieved by using a <meta> tag. A <meta> tag indicate that the document is optimized for mobile devices and are used to control the display scale, while displaying HTML content on the device. It is specific to mobile browsers.
Table 16.3 lists some of the variations of <meta> tag used for different mobile browsers.

Meta Tag     Description     Supported Mobile Browser       
<meta name=”HandheldFriendly” content=”true”/>     Indicates that the content is designed for small-screen handheld devices. The value true prevent the browsers from scaling the content     BlackBerry and others       
<meta name=”MobileOptimized” content=”width” />     Accept width (in pixels) to place the content and forces the layout to one column in the browser     Windows Mobile and Windows Phone       
<meta name=”Apple-mobile-web-app-capable” content=”yes”/>     Indicates that the Web application will run in a full-screen mode     Safari       
<meta name=”Format-detection” content=”telephone=no”/>     Automatic detection of phone numbers is enabled or disabled on Web pages     Safari running on iOS    

         

html tutorials theory


The document structure is represented by a <body> element in an HTML Web page. The <body> element of a mobile Web application defines the content that are displayed to the user. Some of the elements used in the <body> element of a mobile Web page are as follows:
Layouts
The HTML5 new tags that provide semantics for the layout of an HTML document are as follows:
<article> - An independent portion of the document or site
<aside> - Content that is tangential to the main part of the page or site
<figcaption> - Caption for a figure
<figure> - A figure or quotation pulled out of the flow of text
<footer> - The footer of a document or section
<header> - The header of a document or section
<hgroup> - A group of headings
<nav> - A navigation section
<section> - Identifies a block of content
Images
Images can be used in mobile Web applications for pictorial representation. Almost all mobile browsers understand formats, such as GIF, JPEG, and PNG.
However, images should not be used for setting background, buttons, links, or presenting titles on a mobile Web page. This is because images increase the number of request to the Web server and also load time of the Web page.
The <img> tag is used to display image on a Web page. The attributes of <img> tag, such as width, height, and alt should be specified, as it reduces the rendering time of the imag
 Concepts Session 16 Building a Mobile Web Application V 1.1 © zetutorials Limited
Code Snippet 2 demonstrates a mobile Web page with an <img> tag.
Code Snippet 2:

<!DOCTYPE html>
<head>
<title>Images</title>
<meta name=”viewport” content=”width=device-width, user-scalable=no”/>
</head>
<body>
<article>
<h2> Gift Basket </h2>
<img src=”gift.jpg” width=”200” height=”200” alt=”Gift Items” />
</article>
</body>
</html>   
The document structure is represented by a <body> element in an HTML Web page. The <body> element of a mobile Web application defines the content that are displayed to the user. Some of the elements used in the <body> element of a mobile Web page are as follows:
Layouts
The HTML5 new tags that provide semantics for the layout of an HTML document are as follows:
<article> - An independent portion of the document or site
<aside> - Content that is tangential to the main part of the page or site
<figcaption> - Caption for a figure
<figure> - A figure or quotation pulled out of the flow of text
<footer> - The footer of a document or section
<header> - The header of a document or section
<hgroup> - A group of headings
<nav> - A navigation section
<section> - Identifies a block of content
Images
Images can be used in mobile Web applications for pictorial representation. Almost all mobile browsers understand formats, such as GIF, JPEG, and PNG.
However, images should not be used for setting background, buttons, links, or presenting titles on a mobile Web page. This is because images increase the number of request to the Web server and also load time of the Web page.
The <img> tag is used to display image on a Web page. The attributes of <img> tag, such as width, height, and alt should be specified, as it reduces the rendering time of the image.
 Concepts Session 16 Building a Mobile Web Application V 1.1 © zetutorials Limited
Code Snippet 2 demonstrates a mobile Web page with an <img> tag.
Code Snippet 2:

<!DOCTYPE html>
<head>
<title>Images</title>
<meta name=”viewport” content=”width=device-width, user-scalable=no”/>
</head>
<body>
<article>
<h2> Gift Basket </h2>
<img src=”gift.jpg” width=”200” height=”200” alt=”Gift Items” />
</article>
</body>
</html>   

Tuesday, 28 April 2015

CSS for Mobile
CSS3 provides properties for adding colors, selectors, borders, backgrounds, and so on for
effective appearance of a Web page.
Most modern mobile browsers support following features of CSS3:
Rounded corners
Images with borders
Adding shadow effect on text and boxes
Animations
Transitions
Multi-column layout
Apart from W3C specifications that are laid for CSS3, modern browsers have provided new
styles for CSS3. These styles are specific to each browser. Therefore, to add these styles on a
Web page, the relevant properties need to be prefixed with the browser specific keyword.
The property prefixed with the keyword represents the browser on which it is supported.
Table 16.5 lists the keywords with their supported browsers.

Sunday, 26 April 2015

html tutorials session 17

Session 17

Building a Mobile Web Application
You will view and practice how to use HTML5 tags in a mobile Web application.
Working with Viewport and Media Queries in a Mobile Web Application
Working with jQuery Mobile API .

Introduction
Canvas is one of the most interesting features added in HTML5. The <canvas> element supports advanced graphics and interactions in many forms. In earlier versions of HTML, you could achieve this by using plug-ins. Using the <canvas> element eliminates the need for such plug-ins and makes working with graphics easier and more efficient. The <canvas> element is a drawing area where the user can draw graphics, use images, add animations, and also add text for enhancing the user experience on Web pages.
17.2 Canvas Element
The <canvas> element in HTML5 can be used to draw much more than just rectangles on Web sites - it can be used to dynamically draw graphics using JavaScript. This improves the overall performance of Web sites and avoids the requirement to download images from the sites. The <canvas> element is represented like a rectangle on a page and allows the user to draw arcs, text, shapes, gradients, and patterns. By using <canvas>, the user can draw many complex shapes and also apply various effects and transformations.
The <canvas> in HTML5 is like the <div>, <table>, or <a> tag except that the content used in it is rendered through JavaScript.
The <canvas> element is simple and easy to use with JavaScript. The <canvas> element does not contain any drawing abilities, instead, the drawing is done using a JavaScript code. To make use of the <canvas> element, a user has to add the <canvas> tag on the HTML page.
Code Snippet 1 demonstrates the use of <canvas> element.
Code Snippet 1:

<!DOCTYPE HTML>
<html>
<head>
<title> Canvas </title>
<style>
canvas{border: medium double red; margin: 4px}
</style>
</head>
<body>
<canvas width=”278” height=”200”></canvas>
</body>
</html>   

In the code, the <style> element is used to display the border of the <canvas> element. The height and width attributes specify the size of the <canvas> element on the page.


To draw a <canvas> element, the user can use a context object. The context object contains the drawing functions for a specific style of graphics. Two-Dimensional (2d) context is used to work with 2d operations.
The <canvas> element in DOM exposes the HTMLCanvasElement interface. This interface provides the methods and properties for changing the presentation and layout of canvas elements. The HTMLCanvasElement has a getContext(context) method that returns the drawing context for the canvas.
Code Snippet 2 demonstrates the 2d context object for the canvas .


<!DOCTYPE HTML>
<html>
<head>
<title> Canvas </title>
<script>
window.onload = function() {   
 
var canvas = document.getElementById(‘mCanvas’);
var ctext = canvas.getContext(‘2d’);
ctext.beginPath();
ctext.rect(18, 50, 200, 100);
ctext.fillStyle = ”DarkBlue”;
ctext.fill();
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”578” height=”200”></canvas>
</body>
</html>    

In the code, the height and width attributes define the height and width of the canvas element respectively. In the initializer function, the DOM object is accessed through the id attribute and gets a 2d context by using the getContext() method. Here, the rectangle is created by using the rect(18, 50, 200, 100) method with x, y, height, and width parameters and is positioned at left corner of the page .

Drawing a Line in Canvas
You can create lines in a canvas using the stroke(), beginPath(), lineTo(), and moveTo() methods.
The following is the syntax to create a line in canvas:
Syntax:
ctext.beginPath();
ctext.moveTo(x,y);
ctext.lineTo(x,y);
ctext.stroke()
where,
ctext - specifies a context object
beginPath() - Specifies a new drawing path
moveTo() - Specifies the creation of new sub path to the given position
lineTo() - Specifies the drawing of a line from the context position to the given position
stroke() - Specifies how to assign a color to the line and display it
Code Snippet 3 demonstrates creating a line in HTML5 canvas.


<!DOCTYPE HTML>
<html>
<head>
<title>Line</title>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid red;
}
</style>
<script>   
 
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
ctext.beginPath();
ctext.moveTo(100, 150);
ctext.lineTo(250, 50);
ctext.lineWidth = 5;
ctext.strokeStyle = “blue”;
ctext.stroke();
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”360” height=”200”></canvas>
</body>
</html>    


In the code, the height and width attributes are defined. The initializer function has the DOM object which is accessed through the id attribute and gets a 2d context by using the getContext() method. The beginPath() method is called through the context object to draw the path of the line. The moveTo(100, 150) method is called that creates a new path for the given point to place the drawing cursor. This method moves the position of the window to the upper-left corner by giving the x and y coordinates. The lineTo(250, 50) method is called to draw the line from the context point to given point. The lineWidth property is specified as 5 to define the width of the line on the canvas. The strokeStyle property sets the color of the line to blue. The stroke() method assigns the color to the line.

Working with Drawing Objects in Canvas
HTML5 canvas allows the user to work with different types of drawing objects. Following objects can be drawn on a canvas element:
Rectangle
With HTML5 canvas, the user can create a rectangle using the rect() method. The HTML5 canvas is placed by using the x and y parameters and appropriately sized through height and width properties. There is a collection of methods and properties that are used to draw different types of shapes. lists the common properties and methods of various shapes.


Properties and Methods     Description       
fillStyle     The values can be gradient, pattern, or a CSS color. The default property style is solid black, but the user can set the color according to the requirements.       
filRect(x,y,width, height)     Enables the user to draw a rectangle with the existing fill style.       
strokeStyle()     The values can be gradient, pattern, or a CSS color.    
 
Properties and Methods     Description       
s t r o k e R e c t ( x , y , width, height)     Enables the user to draw a rectangle with the existing stroke style. This property is used to draw the edges of the rectangle.       
clearRect(x, y, width, height)    
 
<!DOCTYPE HTML>
<html>
<head>
<style>
#mCanvas {
border: 1px solid green;
}
body {
margin: 0px;
padding: 0px;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(‘mCanvas’);
var ctext = canvas.getContext(‘2d’);
ctext.beginPath();
ctext.rect(30, 50, 150, 100);
ctext.fillStyle = “Magenta”;
ctext.fill();
ctext.lineWidth = 5;
ctext.strokeStyle = ‘black’;
ctext.stroke();   
 
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”278” height=”200”></canvas>
</body>
</html>    


In the code, the height and width attributes are defined. The initializer function has the DOM object which is accessed through the id attribute and gets a 2d context by using the getContext() method. The beginPath() method is called through the context object to draw the rectangle. The rect(30, 50, 150, 100) method takes x, y, height, and width as the parameters. The fillStyle property fills the rectangle with magenta color. The fill() method is used to paint the rectangle. The lineWidth property is specified as 5 to define the width of line on the canvas. The strokeStyle property sets the stroke style of the rectangle to black. The stroke() method assigns the color to the rectangle.
           
Arcs
With HTML5 canvas, the user can create an arc by using the arc() method. Arcs are represented using a start angle, an end angle, a radius, a center point, and the drawing direction (anticlockwise or clockwise).

Canvas and JavaScript V 1.1 © zetutorials Limited The syntax to draw an arc in HTML5 is as follows:
Syntax:
arc(x, y, radius, startAngle, endAngle, anticlockwise)
where,
x, y - Specifies the coordinates of the center of an arc
radius - Specifies the distance from the center to any point on the circle
startAngle, endAngle - Specifies the start and end points in the arc
anticlockwise - Draws the arc clockwise or anticlockwise and accepts a boolean value
Code Snippet 5 demonstrates how to create an arc in HTML5 canvas.


<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid black;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
var x = canvas.width / 2;
var radius = 75;
var startAngle = 1.1 * Math.PI;
var endAngle = 1.9 * Math.PI;
var ctrClockwise = false;   
 
ctext.beginPath();
ctext.arc(x, y, radius, startAngle, endAngle, ctrClockwise);
ctext.lineWidth = 25;
// line color
ctext.strokeStyle = “DarkGreen”;
ctext.stroke();
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”278” height=”250”></canvas>
</body>
</html>    

In the code, the beginPath() method is called through the context object to draw an arc by using the arc() method which has x, y, and radius as the parameters. The x and y are the coordinates of the circle, radius is the distance from the center to draw the arc on the canvas. The startAngle and the endAngle are the start and end points of the arc respectively. The anticlockwise specifies the direction of the arc between the two start and end points.

Circle
In HTML5, you can draw a circle using the arc() method. You have to set the start angle with 0 and the end angle is specified as 2 * PI.
The following is the syntax to draw a circle in HTML5 is as follows:
Syntax:
arc(x, y, radius, startAngle, endAngle, anticlockwise)
where,
x, y - Specifies the coordinates of the center of a circle
radius - Specifies the distance from the center to any point on the circle
startAngle, endAngle - Specifies the start and end points in the circle
anticlockwise - Draws the circle clockwise or anticlockwise and accepts a boolean value

Code Snippet 6 demonstrates how to create a circle using HTML5.


<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid blue;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
var ctrX = canvas.width / 2;
var ctrY = canvas.height / 2;
var radius = 70;
ctext.beginPath();
ctext.arc(ctrX, ctrY, radius, 0, 2 * Math.PI, false);
ctext.fillStyle = “DarkOrchid”;
ctext.fill();
ctext.lineWidth = 4;
ctext.strokeStyle = “black”;
ctext.stroke();
};
</script>
</head>   
 
<body>
<canvas id=”mCanvas” width=”356” height=”150”></canvas>
</body>
</html>    

In the code, a circle is defined by using the arc() method which has ctrX, ctrY, and radius as the parameters. To define the arc with the points the startAngle is set to 0 and the endAngle is specified as 2*PI. The anticlockwise defines the direction of the path of an arc between the two start and end points.

Bezier Curves
Using HTML5 canvas, you can create a Bezier curve using the bezierCurveTo() method. Bezier curves are represented with the two control points, context points, and an end point.
Code Snippet 7 demonstrates how to create a Bezier curve using HTML5.


<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;    
 
padding: 0px;
}
#mCanvas {
border: 1px solid maroon;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
ctext.beginPath();
ctext.moveTo(188, 130);
ctext.bezierCurveTo(140, 10, 388, 10, 288, 100);
ctext.lineWidth = 15;
// line color
ctext.strokeStyle = “purple”;
ctext.stroke();
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”378” height=”200”></canvas>
</body>
</html>    

In the code, the Bezier curve uses the bezierCurveTo() method. This method defines the current context point, two control points, and an end point. The context point uses the moveTo() method. The first portion of the curve is tangential to the imaginary line defined in the context point and first control point. The second portion of the curve is tangential to the imaginary line which is defined by the second control point and the ending point.
Quadratic Curves
HTML5 canvas allows the user to create quadratic curves using the quadraticCurveTo() method. Quadratic curves are represented through the context point, an end point, and a control point.
Code Snippet 8 demonstrates how to create a quadratic curve using HTML5.


<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid #9C9898;
}    
 
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
ctext.beginPath();
ctext.moveTo(178, 150);
ctext.quadraticCurveTo(220, 0, 320, 150);
ctext.lineWidth = 15;
// line color
ctext.strokeStyle = “Fuchsia”;
ctext.stroke();
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”378” height=”200”></canvas>
</body>
</html>    

In the code, the control point defines the curve of the quadratic by two tangential lines that are connected to both the context point and the end point. The context point is represented using the moveTo() method. This method moves the control point from the context point and the end point to create a sharper curve. It also moves the control point close to the context point and end point to create broad curves.
Working with Images
In HTML5, the user can draw image objects on canvas using the drawImage() method. The drawImage() method can also draw parts of an image and increase or reduce the size of the image. This method accepts nine parameters, depending on editing that is required on the image. The image object can be a video, an image, or another canvas element.
Code Snippet 9 demonstrates how to create an image using HTML5.


<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
var imgObj = new Image();
imgObj.onload = function() {
ctext.drawImage(imgObj, 69, 50);
};
imgObj.src = “bird.jpg”;
};
</script>
</head   
 
<body>
<canvas id=”mCanvas” width=”368” height=”300”></canvas>
</body>
</html>    

Code Snippet 10 demonstrates how to resize images with height and width attributes

<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid black;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
var x = 69;
var y = 50;
var w = 150;
var h = 137;
var imgObj = new Image();
imgObj.onload = function() {
ctext.drawImage(imgObj, x, y, w, h);
};
imgObj.src = “bird.jpg”;
};
</script>
</head>
<body>   

Working with Text
HTML5 canvas enables you to set the font, style, and size of text by using the font properties. The font style can be italic, normal, or bold. For setting the text color, you can use the fillStyle property of the canvas.
Code Snippet 11 demonstrates how to set the font, size, style, and color of the text on a HTML5 canvas .

<!DOCTYPE HTML>
<html>
<head>
<style>
body {

margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid blue;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
ctext.font = “italic 30pt Calibri”;
ctext.fillStyle = “MediumVioletRed”;
ctext.fillText(“Welcome to HTML5!”, 40, 100);
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”380” height=”170”></canvas>
</body>
</html>    
   

In the code, the font text is specified as Calibri, style as italic, and size is set to 30pt. The fillStyle property specifies the text color and the fillText property is used to set the text on the canvas.

In HTML5 canvas, the user can set the stroke color by using the strokeText() method and strokeStyle property of the canvas context.
Code Snippet 12 demonstrates the use of stroke text in HTML5 canvas.


<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid black;
}
</style>
<script>
window.onload = function() {   
 
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
var x = 80;
var y = 110;
ctext.font = “40pt Calibri”;
ctext.lineWidth = 2;
// stroke color
ctext.strokeStyle = “Brown”;
ctext.strokeText(“HTML5”, x, y);
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”360” height=”200”></canvas>
</body>
</html>    

In the code, the stroke color is set by using the strokeStyle property and the strokeText() method.

Using Transparency for Text in Canvas
There are two ways to set the transparency for the text and shapes. The first method is to use the strokeStyle and fillStyle by using the rgb function. The second method is to use globalAlpha drawing state property, which can be applied universally. The globalAlpha property is a value that ranges between 0 (fully transparent) and 1 (fully opaque).
Code Snippet 13 demonstrates the use of globalAlpha property.


<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mCanvas {
border: 1px solid black;
}
</style>
<script>
window.onload = function() {
var canvas = document.getElementById(“mCanvas”);
var ctext = canvas.getContext(“2d”);
ctext.fillStyle = “Indigo”;
ctext.strokeStyle =”black”;
ctext.lineWidth=2;
ctext.font = “italic 30pt Calibri”;
ctext.fillText(“HTML5”, 40, 100);
ctext.strokeText(“HTML5”, 40, 100);

ctext.fillStyle=”blue”;
ctext.globalAlpha=0.5;
ctext.fillRect(100, 10, 150, 100);
};
</script>
</head>
<body>
<canvas id=”mCanvas” width=”350” height=”170”></canvas>
</body>
</html>    
   

 In the code, the fillStyle and strokeStyle is used to color the text. The ‘HTML5’ text lineWidth is specified as 2 and the font-family is set to Calibri with italic style and font-size to 30pt. The fillText property fills the color and strokeText property applies the stroke color to the HTML5 text. The fillStyle is set to blue and globalAlpha property is set to 0.5. The fillRect(100, 10, 150, 100) specifies the x, y, height, and width of the rectangle .

Using Events with jQuery
jQuery also offers different events to deal with common interactions when the user moves the mouse or switch between two actions while clicking.
hover() event
The mouseenter and mouseleave are the two events often used together. For example, when a user moves a mouse over a menu, a tooltip appears and when the user moves the mouse off the menu, the tooltip disappears. Combining these two events is very common, therefore, jQuery provides a hover() function that accepts two parameters. The first parameter executes when the mouse moves over the element and the second function executes when the mouse moves away from the element.
Code Snippet 14 demonstrates the hover event .


<!DOCTYPE html>
<html>
<head>
<script src=”jquery-1.7.2.min.js”></script>
<script>
$(document).ready(function(){
$(“p”).hover(function(){
$(“p”).css(“background-color”,”red”);
},function(){
$(“p”).css(“background-color”,”maroon”);
});
});
</script>
</head>
<body>
<p>Hover the mouse on this line.</p>
</body>
</html>    

In the code, the hover() method is used. When the mouse is placed on the text, then the background color changes to red. Similarly, when the user moves the mouse outside the text, the background-color changes to maroon.

The toggle() event
The toggle() event works in a similar manner as that of the hover() event, except that it responds to mouse clicks. The toggle() function accepts more than two functions as arguments. For example, you want to perform some action on the first click, another action on the second click, and one more action on the third click. All the functions passed to the toggle() event will react to its corresponding click action.


<!DOCTYPE html>
<html>
<head>
<script src=”jquery-1.7.2.min.js”></script>
<script>
$(document).ready(function(){
$(“p”).toggle(function(){
$(“body”).css(“background-color”,”blue”);},
function(){
$(“body”).css(“background-color”,”pink”);},
function(){
$(“body”).css(“background-color”,”grey”);}
);
});
</script>
</head>
<body>
<p>Click to change the colors.</p>
</body>
</html>    

In the code, the toggle() method is used. When the user clicks the text then the background-color of the document is changed to blue, pink, and grey respectively.

Inclusion of External Content in Web Pages
HTML5 introduces the <eventsource> tag that allows the user to push external content in the Web page. This model is referred to as push model. Since the <eventsource> tag is not supported in many browsers, users make use of the <embed> tag for this purpose. The <embed> tag is a new element in HTML5 and it is represented as a container for an interactive content or an external application. The <embed> tag is often used to add elements such as image, audio, or video on a Web page.
Code Snippet 16 demonstrates the use of the <embed> tag.



html tutorials session 18

Session 18 :
Introduction
Consider an e-mail client, such as Gmail. To log in to your mail account in Gmail, you need to enter your username and password.


As shown in figure 18.1, the Stay signed in check box, specifies that the login details, such as Username and Password, should be remembered by the computer.
Traditionally, over the last few decades, Web applications have been using cookies to store small amounts of information on a user’s computer. A cookie is a file that stores user-related information and may either be temporary or permanent. Thus, in this case, a cookie can be created for login details which can be saved for a specified period on a user’s computer.
However, the drawbacks of cookies are as follows:
Cookies slow down the performance of Web application, as they are included with every HTTP request.
Cookies cannot be considered as safe means for transmission of sensitive data.
Cookies cannot store large amount of information, as they have a limitation of size of 4 KB.
To overcome these drawbacks and offer a solution to store data on the client-side, W3C has designed a specification named Web Storage API.

The Web storage provides the functionality using which data can be stored on the client-side for a session or beyond the session.

Web Storage in HTML5
Web storage is a W3C specification. It provides functionality for storage of data on the client-side that is on user’s machine. This data can cater for both temporary as well as permanent needs. Certain browsers also refer to it as ‘DOM Storage’. The advantage of such storage is that it offers more control than traditional cookies, and is easy to work with.
Web storage was originally a part of the HTML5 specification, but now it is present in a separate specification. It enables to store a maximum of 5 MB of information per domain.
HTML5 Web applications make use of Web storage to implement client-side persistent storage.
18.2.1 Web Storage versus Cookies
There are some key differences between cookies and Web storage that are as follows:
Cookies are meant to be read on the server-side, whereas Web storage is available only on the client-side. The server cannot read or write to it directly.
Cookies are sent along with each HTTP request to the server, whereas Web storage data is not carried over to the server.
Cookies can result in bandwidth overhead and thus lead to high costs, as they are sent with each HTTP request. The Web storage is stored on the user’s hard drive, so it costs nothing to use.
As mentioned earlier, with cookies, the information data that could be stored is 4 KB, whereas with Web storage, a large amount of data can be stored upto 5 MB.
18.2.2 Browser-specific Web Storage
Web storage is browser-specific. If a user visits a site in Google Chrome, any data will be stored to Google Chrome’s Web storage store. Similarly, if the user revisits that same site in Firefox, the data saved earlier through Google Chrome will be unavailable. The location where the Web storage data is stored depends on the browser. Each browser’s storage is separate and independent, even if it is present on the same machine.
HTML5 Web storage is implemented natively in most Web browsers, so one can use it even when a third-party browser plug-in is not available.


Exploring Web Storage
The two types of HTML5 Web storage are namely, session storage and local storage. Both session and local storage enable to store around 5 MB of data per domain. Before going into the details of these types, you need to determine, if the current version of your browser has support for HTML5 Web storage.
To check for browser support of HTML5 Web storage, a property named localStorage or sessionStorage is available as a global variable for the window object. If there is no support, the localStorage or sessionStorage property will be undefined.
Code Snippet 1 demonstrates the script to check the support for HTML5 Web storage in the browser.
Code Snippet 1:

<!DOCTYPE html>
<html>
<head>
<title>Support for Web Storage</title>
<script>
function checkSupport()
{
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null)
{
alert(“Your browser supports Web Storage”);
return;
}
alert(“Your browser does not support Web Storage”);    
 
}
</script>
</head>
<body onload=”checkSupport();”>
</body>
</html>    


Here, in the code, the if statement checks whether a property named sessionStorage exists in the global window object. If the property exists, it means that session storage is supported and an appropriate message is displayed to indicate the same. If however, the property does not exists, it means session storage is not supported on that browser, and an appropriate message is displayed to indicate the same.
Figure 18.2 shows the Web storage support.
Figure 18.2: Web Storage Support
18.3.1 Session Storage
Session storage keeps track of data specific to one window or tab and discards it as soon the user closes the tab (or window) that he/she was working with. Thus, even if you are visiting the same site in two different windows, each window will have its own individual session storage object. This means that each window contains separate session storage object with distinct data. Session storage lasts for the entire duration of the session and hence, is not persistent.
Session storage makes use of named key/value pairs. The data is stored using the named key, whereas the data is retrieved by referring to that key. Both the key-value pairs are enclosed within double quotes.
The key is a string, whereas the value stored in the key can be of any type of data, such as string, boolean, integer, or float. Regardless of the type of data that is stored, it is actually stored internally as a string.
Therefore, storing and retrieving data of other types requires the use of functions to convert them into the appropriate data types.

For example, the function, parseInt() is used to convert data into an appropriate JavaScript data type.


Key     Value       
Name     Sarah       
book     C Programming       
Email     info@me.com       
car     Toyota Innova       
age     28       
uservalid     true    

There are several operations that can be performed with the sessionStorage object. These operations are described as follows:
Storing and retrieving data
The setItem() and getItem() methods are used to store and retrieve data from session storage respectively.
The syntax to use the setItem() and getItem() methods is as follows:
Syntax:
To assign data
sessionStorage.setItem(key, value);
where,
key: Is the named key to refer to the data
value: Is the data to be stored
To retrieve data
var item = sessionStorage.getItem(key);
where,
item: Is the variable into which the data will be saved
key: Is the named key to refer to the data


<!DOCTYPE html>
<html>
<head>
<title>Working with Session Storage</title>
<script>
function testStorage()
{
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null)
{
sessionStorage.setItem(‘name’, ‘Sarah’);
alert(‘The name is: ‘ + sessionStorage.getItem(‘name’));
}
}
</script>
</head>
<body onload=” testStorage();”>
</body>
</html>    





Key names need not necessarily be given as strings. Even, a number can be specified as a key name, though internally while storing, it will be converted to a string.
Code Snippet 3 shows the script that uses number as the key.
Code Snippet 3:

<script>
function testStorage()
{
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null)
{
sessionStorage.setItem(6, ‘The book was wonderful’);
var feedback = sessionStorage.getItem(6);
alert(feedback);
}
}
</script>    



Here, in the code, the key is set to a numeric value 6, but that does not mean that it is the sixth key. The name of the key is defined as 6 that is stored internally in the browser. The getItem() method is used to retrieve the value stored with that key. Finally, the value having the key as 6 is displayed in the alert window.529 of 590 Concepts Session 1HTML5 Web Storage 
Figure 18.4 shows the output that retrieves value stored at the key, 6.
Figure 18.4: Output – Retrieves Value Stored at Key 6
Similar to other JavaScript objects, the sessionStorage object can be treated as an associative array. Instead of using the getItem() and setItem() methods, an array subscript can be used to retrieve and assign the data. For example, sessionStorage.setItem(‘name’,’John’); can be written as sessionStorage[‘name’] =’John’;
Similarly, alert (sessionStorage.getItem(‘name’)); can be written as alert (sessionStorage[‘name’]);
As mentioned earlier, it is also possible to store non-string values into session storage.
Code Snippet 4 demonstrates the storage of an integer value for age and is later retrieved by using parseInt() method along with the getItem() method.


<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8”>
<title> Session Storage </title>
<script>
function store() {
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null) {
var name = document.getElementById(‘name’).value;
sessionStorage.setItem(‘username’, name);
var data = sessionStorage.getItem(‘username’);   



A database is an organized collection of data. Databases, such as relational database stores the data in the form of tables. A table comprises rows and columns that are used to store data. The representation of data from a table is in the form of records.
HTML5 has introduced a new Web Storage API which can host Web databases locally within the user browser. However, Web databases are not like relational databases in terms of functionality.
Indexed Database API is a specification also known as IndexedDB. It is basically an object store that can be used to store and manipulate data on the client-side. The object store is the primary storage mechanism that stores the object in the database managed locally within the browser. It enables to create an object store of a particular type in which objects can be persisted using JavaScript. Thus, IndexedDB enables to create Web applications with rich query abilities and which can work both online and offline.
IndexedDB supports two types of API namely, synchronous and asynchronous. The synchronous API can be used with WebWorkers, whereas asynchronous API can be used for Web applications. Currently, no major browsers provide the support for synchronous API.
The IndexedDB API is implemented using window.indexedDB object. As the current specification is still in the evolving stage, browsers implement the IndexedDB object with their own prefixes. For example, Chrome browser uses the webkit prefix, whereas Mozilla supports –moz prefix.
IndexedDB API
Some of the basic constructs of IndexedDB API are as follows:
Database - The IndexedDB database comprises more than one object store. Each database contains a name that identifies the origin of the database and a version number which identifies the lifetime of the database.
Object Store - Object store is the main mechanism to store data in a database. They hold the data stored in the database in the form of records.
Keys - Each record stored in the database is identified by a unique key.
Values - Values are the data stored in the records.
Key Path - A key path is a string that defines how the browser should extract key from a value. The key from a value can be extracted either in the object store or index. An empty string, a JavaScript identifier, and so on is some of the valid key paths.
Index - It is used when the data from the object store is retrieved based on some other values other than a key. It is a specialized object store which searches for records in another object store known as referenced object store.
Transaction - Any addition or retrieval of the data in a database is performed by using transaction. In other words, it is a mechanism used for interacting with the database. Each transaction has a mode, scope, and a request list. The mode determines the type of transaction that can be performed, scope identifies the object store on which the transaction will be performed, and finally request list determines the requests that have been made.
Requests - Operations, such as reading or writing on the database is performed using a request. Each request contains attributes, such as flag, source object, result, and error.
Cursor - Cursor is a mechanism used to retrieve multiple records from a database.
Key Range - Records from the object stores and indexes are retrieved using keys or key ranges. A key range refers to retrieval of data between specified bounds based on the keys
Implementing IndexedDB API
The steps to implement the IndexedDB API in a Web application are as follows:
Open a database
Create an object store
Start a transaction
Perform some database operations, such as add and retrieve
Work with the retrieved results
Opening a Database
Code Snippet 7 shows the code to open a database.
Code Snippet 7:

var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
var request = indexedDB.open(“CompanyDB”, 1);
request.onsuccess = function (event) {
. . .
};
request.onerror = function (event) {
console.log(“IndexedDB error: “ + event.target.errorCode);
};    


Creating the Object Store
The structure of IndexedDB database facilitates the storage of multiple object stores. In other words, there can be more than one object stores in the database. Object store is created using createObjectStore() method. The createObjectStore() methods accepts two arguments namely, the store name and a parameter object. The parameter object is used for defining an optional property which is important. In this case, a key path is defined that is used for identifying unique objects in the object store. For example, an employee store contains the id property as key path, which will be unique for each object and must be present for each object.

HTML5 Web Storage  Limited Code Snippet 9 demonstrates the code to create an object store named employee in the CompanyDB database.
Code Snippet 9:

var employeeData = [
{ name: “John Smith”, email: “john@company.com” },
{ name: “Jill Patrick”, email: “jill@company.com” },
{ name: “Rock Ethan”, email: “rock@company.com” },
{ name: “Daniel Andrew”, email: “daniel@company.com” }
];
var objectStore = db.createObjectStore(“employee”, {
keyPath: “id”, autoIncrement: true });
for (i in employeeData) {
objectStore.put(employeeData[i]);
alert(“Record added”);
}    


The code creates an array named employeeData containing name and e-mail values. Then, the createObjectStore() method creates an employee store with its key path set to id attribute. The key path is used with autoIncrement option that automatically generates id for each of the objects. All the individual objects in the object store are identified based on the id. Finally, the for..in loop stores the data in the employee object store.
Creating a Transaction
To perform database operation, such as retrieving data from the object store, IndexedDB provides a IDBTransaction object. This object can be created in three mode namely, read-only, read-write, and snapshot. The read-write mode is used to update the object, whereas read-only mode is used for other operations.

Code Snippet 10 demonstrates the code to retrieve data from the employee object store using the get() function of the transaction object.
Code Snippet 10:

var trans = db.transaction([“employee”], IDBTransaction.READ_ WRITE).objectStore(“employee”);
var request = trans.get(2);
request.onerror = function(event) {
// Handle errors!
};
request.onsuccess = function(event) {
// Do something with the request.result!
alert(“Name: “ + request.result.name);
};    

In the code, the transaction() method accepts two parameters. The second parameter is optional. The first parameter is the list of the object stores that are extended by the transaction object. In this case, there is a single object store named employee, created in the database. The optional second parameter specifies the type of the transaction, that is, read-only, read-write, or snapshot. Here, the transaction type is defined as IDBTransaction.READ_WRITE. This type allows reading as well as writing in the database. The employee object store is retrieved from the transaction object on which operations are performed. Here, the get() method is invoked on the employee object store which returns the value against the key path 2. Finally, the result of the get() method is stored in the request object on which callback functions, such as onsuccess and onerror are invoked.
Opening a Cursor
Cursor is used to retrieve multiple records from an object store. They can be used when the value of key path is not known. They are part of a transaction and are opened for a particular object store.
 540 of 590 Concepts Session 1HTML5 Web Storage V 1.1 © zetutorials Limited
Code Snippet 11 demonstrates the code to retrieve multiple records from the employee object store.
Code Snippet 11:

store = db.transaction(“employee”).objectStore(“employee”);
store.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert(“Name for id “ + cursor.key + “ is “ + cursor.value.name);
cursor.continue();
}
};    
 
Native Apps     HTML5 Apps       
Native Apps runs on iOS and Android devices that can be downloaded or purchased from the online app stores.     HTML5 Apps runs on a Web server, usually in a Web browser.       
Native Apps use programming language, such as Java for Android devices and Objective C for iOS devices.     Web developers use HTML, JavaScript, and CSS. They need to acquire the skills of Java and objective C for writing native applications.    

Advantages of HTML5 Apps
The main advantage of using HTML5 is to create applications that execute on a wide range of devices easily. App development on HTML5 is cheaper as compared to native app development. Developers do not have to learn any new programming language and the development becomes much easier.
There are many reasons to develop HTML5 applications rather than native applications. Some of the reasons are as follows


Users cannot identify the differences
There are many instances where the users cannot identify whether they are working on a hybrid HTML5-native application or a fully native application or an HTML5 application.

Users adjust styles for devices
HTML5 apps can be viewed on any devices that contains Web browser. Users can also use CSS3 for applying styles to change the look according to their requirements. HTML5 apps look similar to Web pages by using the same code.
Upcoming functionalities
HTML5 does not support all features on a device, but it is coming up with new functionalities. There are several APIs that exist for working on local databases, Web storage, drag-and-drop, offline Web pages, and many more. New APIs are being planned in future to provide Web pages access to the software and hardware of a device.
Improving performance
Many developers learn new methods to improve the performance of Web pages. These same methods are useful to mobile HTML5 apps. There are many apps, such as timer, mail, databases, and news apps that need not be faster.
Independent device
HTML5 apps work on mobile devices as well as Web browsers, as it is important for development purpose. There are millions of laptop and desktop users than mobile users. If the developers want that their application to be used by a large number of users, then they should design and develop the application for both mobile users as well as desktop users.
Developers are not locked in app stores
There are a number of app stores existing for Android and BlackBerry. If developers wish to sell the apps, then they are required to provide them into as many stores or marketplaces as possible. By using HTML5, developers are not restricted to an app store. Instead, they can create applications and sell them like any other Web application.
HTML5 app acts a substitute to native apps, though in several conditions, native apps can be used for better purpose. Developers can create hybrid applications that are a combination of native and HTML apps.
18.6.3 Advantages of Native Apps
The major advantage of native apps over HTML5 apps is that they are faster than HTML5 apps. Similar to normal Web pages, HTML5 apps are slow, because these apps work on HTTP that uses a request/response cycle mechanism. When an HTTP request is made, it takes more time for the applications to execute as it has to wait for the request to go and return back with a response.

Advantages of Native Apps
The major advantage of native apps over HTML5 apps is that they are faster than HTML5 apps. Similar to normal Web pages, HTML5 apps are slow, because these apps work on HTTP that uses a request/response cycle mechanism. When an HTTP request is made, it takes more time for the applications to execute as it has to wait for the request to go and return back with a response.
     54of 590 Concepts Session 1HTML5 Web Storage V 1.1 © zetutorials Limited
Native apps provide many more benefits over HTML5 apps. These benefits are as follows:
Providing access to device hardware
Many mobile devices contain hardware, such as accelerometer, GPS, a camera, and so on. The GPS is accessible through Geolocation API. At present, there are no APIs available for accelerometers, cameras, or any other device hardware for HTML5 apps.
Uploading Files
Native apps can access the file system in Android and some files in iOS. However, the HTML5 file API does not work on Android or iOS.
Push Notifications
The push notifications are sent always with an open Internet Protocol (IP) connection to applications on the iOS device. Android also has a same feature named Cloud to Device Messaging.
Accessing device files
Native apps communicate with files on devices, such as contacts and photos. However, these files cannot be seen from HTML5 apps.
Superior graphics than HTML5
HTML5 has a <canvas> element, but it will not be able to create a full 3D experience.
Offline access
HTML5 provides access to offline Web applications. However, a native app is stored on local machine, so the users do not require access to the Web to work with the application.
In-app purchasing and advertising
HTML5 apps allow developing in-app stores and advertising. Native apps have these features pre-built in them through app stores. Selling the apps in app store is easy, as HTML5 apps are Web pages that are difficult to sell.
Native apps have an additional benefit, that is trust. Several users are comfortable using application downloaded from app stores than using a Web page. These app stores are preferred than search engines, by the users for finding tools.
       54of 590 Concepts Session 1HTML5 Web Storage V 1.1 © zetutorials Limited
18.6.4 Converting HTML5 Apps to Native Apps
Users have a choice of developing their application in HTML5 and then converting them into a native app. This choice has many combined benefits of HTML5 apps and native apps. Users can use tools to convert HTML5 app to a native app.
The following are the best tools used for converting an HTML5 app to native app:
PhoneGap
PhoneGap is an HTML5 app that allows the user to create native apps with Web technologies and is accessible to app stores and APIs. PhoneGap controls the Web technologies.
Appcelerator
Appcelerator is a cross-platform mobile application development support. It allows the users to create Android, iOS, and mobile Web apps. Native applications are developed using a JavaScript code base with Eclipse as the IDE.

Converting HTML5 Apps to Native Apps
Users have a choice of developing their application in HTML5 and then converting them into a native app. This choice has many combined benefits of HTML5 apps and native apps. Users can use tools to convert HTML5 app to a native app.
The following are the best tools used for converting an HTML5 app to native app:
PhoneGap
PhoneGap is an HTML5 app that allows the user to create native apps with Web technologies and is accessible to app stores and APIs. PhoneGap controls the Web technologies.
Appcelerator
Appcelerator is a cross-platform mobile application development support. It allows the users to create Android, iOS, and mobile Web apps. Native applications are developed using a JavaScript code base with Eclipse as the IDE.







Saturday, 25 April 2015

Html tutorials session 19

 There are different sources through which devices can determine the information about the location. These are as follows:
GPS - GPS is a satellite navigation system that provides information about the location on any part of the globe. The GPS system is maintained by the government of the United States and is used by modern mobile devices with GPS capability.
IP Address - Location information can be derived from IP Address. The IP Address is assigned to devices, such as desktops, printers, and so on connected on a network.
GSM/CDMA Cell IDs - These are used by the cell phones.
WiFi and Bluetooth MAC address - These are used by devices that have wireless network connection.
User Input - It is a software tool which can be used on any device requesting for location information. The information retrieved by the tool is based on the data provided by the user, such as, a zip code.
19.3 Geolocation API
In HTML5, the Geolocation API is a specification provided by W3C. It provides a consistent way to develop location-aware Web applications.
The Geolocation API provides a high-level interface that can be used by developers to retrieve location information related to the hosting devices. The interface hides the details, such as how the information is gathered or which methods were used to retrieve the information. This helps the developer to concentrate on geographic information rather than its processing methods.
The object that holds implementation of the Geolocation API is the Geolocation object. This object is used in JavaScript to retrieve the geographic information about the devices programmatically. The browser processes the script and returns the location to the Geolocation API.
The Geolocation API is supported on most of the modern browsers available on desktop and mobile phones.
Implementing Geolocation Object
The Goelocation object is available as a new property of the navigator object. The navigator object is a browser object that allows a user to retrieve information about the specific location.
The syntax shows how to create a Geolocation object in JavaScript.
Syntax:
var geolocation = window.navigator.geolocation;
where,
window: Is the top level object in JavaScript object hierarchy
Code Snippet 1 demonstrates the script that tests the existence of Geolocation object within a browser.
Code Snippet 1:


<!DOCTYPE html>
<html>
<head>
<title> Testing Support for Geolocation in Browsers</title>
<script>
function display_location_enabled()
{       
// Default message
var str = “Geolocation is not supported in this browser”;

if (window.navigator.geolocation)
{
str = “Geolocation is supported in this browser”;
}
alert (str);
}
</script>
</head>
<body>
<input type=”button” value=”Geolocation Support”
onClick=”display_location_enabled()”></input>
</body>
</html>    
   
In the code, the if statement checks existence of the geolocation property in the browser. If the browser provides an implementation for the property, then an alert window displays the message ‘Geolocation is supported in this browser’. Otherwise, the default message is displayed.
Figure 19.2 shows the existence of Geolocation object in the Chrome browser



Geolocation Methods
The Geolocation object provides three methods that can be used to determine the current position of the user.


Method     Description       
getCurrentPosition()     Retrieves the current geographic location information of the user       
watchPosition()     Retrieves the geographic information of the device at regular intervals   


HTML5 Geolocation and APIs V 1.1 


Method     Description       
clearWatch()     Terminates the current watch process    
Retrieve User Position
The current position of a user is retrieved using the getCurrentPosition (successCallback, errorCallback, options) method. This function accepts three parameters, out of which two are optional, errorCallback and options.
The first parameter, successCallback is the name of the function which is invoked after the position of a device is found successfully. The second parameter, errorCallback is the name of the function which will be called, if an error occurs in retrieving the position. The last parameter, options represents a PositionOptions object.
Code Snippet 2 demonstrates the markup that will retrieve the current location of the user.

<!DOCTYPE html>
<html >
<head>
<title>Geolocation API</title>
<script>
function getLocation()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
alert (“Geolocation is not supported in this browser.”);
}
}


function showPosition(position)
{
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ + ‘Longitude:
‘ + position.coords.longitude);
}
</script>
</head>
<body>
<input type=”button” value=” Display Location”
onClick=”getLocation()”/>
</body>
</html>    


   

In the code, the getCurrentPosition() function obtains the position which is passed as a parameter to the showPosition() function. The showPosition() function obtains the coordinates of a location through position object.
The position object is defined in the Geolocation API and holds the current location of the device. It contains attribute named coords that retrieves the latitude and longitude of the location. The values retrieved for latitude and longitude are in decimal degrees.


Attribute     Description       
coords     An object of type Coordinates that provides different properties, such as latitude, longitude, altitude, accuracy, speed, and so on       
timestamp     An object of type DOMTimeStamp    

Handling Errors
An application could fail in gathering geographic location information. In that case, the Geolocation object calls an errorCallback() function. The errorCallback() function handles errors by obtaining a PositionError object from the API.
PositionError Object
The PositionError object holds information related to errors occurred while finding the geographic location of the user.


Property     Description       
code     Returns a numeric value for the type of error occurred       
message     Returns a detailed message describing the error encountered. The message can be used for debugging    
 
<!DOCTYPE html>
<html>
<head>
<title>Handling Error</title>
<script>
function getLocation()
{
function showPosition(position)
{
alert(‘Latitude: ‘ + position.coords.latitude + ‘\n’ +
‘Longitude: ‘ + position.coords.longitude);
}
function errorHandler(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert (‘You have denied access to your position.’);
break;
case error.POSITION_UNAVAILABLE:
alert (‘There was a problem getting your position.’);
break;
case error.TIMEOUT:
alert (‘The application has timed out attempting to
get your position.’);
break;
}
}
</script>   

 
</head>
<body>
<input type=”button” value=”Display Location”
onClick=”getLocation()”/>
</body>
</html>    
In the code, if the application fails to find the current location of the user, then the errorHandler() function is invoked. The function is passed as the second parameter in the getCurrentPosition() method and is used to handle the errors occurred in the application. It obtains the error object which is of type PositionError from the API and compares it with the error codes specified in the switch-case statement. Depending on the error that has occurred, the appropriate case statement is executed and an alert message is displayed to the user.
Figure 19.5 shows the output displaying error message for geolocation application. The reason for displaying error is that the Chrome browser blocks the URL whose file path starts with file:///.


PositionOptions Object
PositionOptions object is an optional third parameter passed to the getCurrentPosition() method. This object defines properties that are optional and are used by an application while retrieving the geolocation information.


Attribute     Description       
enableHighAccuracy     Indicates that the application wants to receive the most accurate results for geolocation. The default value of the attribute is false   



 
Attribute     Description       
maximumAge     Obtains the cached position object whose age is less than the specified maximumAge limit (in milliseconds). If age limit is set to 0, then the application must obtain a new position object       
timeout     Indicates the maximum time length (in milliseconds) for which the application can wait to obtain the position object       
<script>
var options = {
enableHighAccuracy: true,
maximumAge: 50000,
timeout: 60000
};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,
errorHandler, options);
}
else{
alert (“Geolocation is not supported in this browser.”);
}
}
. . .
</script>    



n the code, an object named options is set with attributes. The attribute maximumAge enables the application to use a cached position object which is not older than 50 seconds. Also, the timeout limit is set to 60 seconds for an application, before notifying an error.
The options is passed as third parameter to the getCurrentPosition() method.

Google Maps API
The Google Maps API is used to display locations on a map based on the values of their coordinates - latitude and longitude. The Google Maps API must be configured in JavaScript, before it can be referenced further on the page. It contains a Map object which is instantiated and displayed on a Web page.
The syntax shows the configuration of Google Maps API in JavaScript.
Syntax:
<script src=”http://maps.google.com/maps/api/js?sensor=false”>
</script>
where,
src: Is the URL of Google Maps API
sensor: Parameter sent with the URL. It indicates whether application uses any sensor, such as GPS system to obtain the location of a user. Its value must be explicitly set to true or false
Code Snippet 5 demonstrates how to load and initialize the Google Maps API in the <script> tag. The code will execute after the page is loaded completely and will invoke a function in response to the onload event.

<!DOCTYPE html>
<html>
<head>
<title> Load and Initialize Google Maps </title>
<style>
html { height: 100% }
body { height: 100%; width: 100%; margin: 10% }
#map_canvas { height: 50%; width: 50% }
</style>
<script src=”http://maps.google.com/maps/api/js?sensor=false”></ script>
<script>   


In the code, the URL “http://maps.google.com/maps/api/js?sensor=false” definesall symbols and definitions to be loaded for the Google Maps API. Then, the function initialize() is invoked after the page is loaded completely. This function creates the object of type Map and initializes it with the map initialization variables.
In the function, var myOptions = {}, is an object of type options that contains properties, such as zoom, center, and mapTypeId. These properties are used to initialize the map.
Then, the statement new google.maps.Map (document.getElementById (“map_canvas”), myOptions); creates an instance of Map object. The object is displayed in a container on the Web page specified with the <div> element.

Finally, to display an icon on the identified location on the Google maps, the Marker object is created. The Marker object’s constructor sets the value for the properties, such as position, map, and title. The position property is specified with the location of the marker on the map. The map property is specified with the Map object to attach the marker with the map. Also, the title property sets the title to be displayed as a tooltip on the map.
As mentioned earlier, the myOptions object has several properties.


Property     Description       
zoom     Sets the initial resolution at which map is displayed. A lower zoom value 0 represents a full map of the Earth. Similarly, a higher zoom value displays a map with high resolution. In Code Snippet 5, the zoom level is set to 16.       
center     Centers the map on a specific point by creating an object of type LatLng which holds the location coordinates. In Code Snippet 5, the map is centered with the location coordinates 51.528663,- 0.173171. These coordinates display a map centered on Lord’s Cricket Ground in London, England.       
mapTypeId     Sets an initial map type. The map types supported are: ROADMAP for normal, SATELLITE for photographic tiles, HYBRID for roads and city names, and TERRAIN for water features. In Code Snippet 5, the map type has been set as google.maps.MapTypeId.HYBRID.    

Tracking User’s Location on Google Maps
The Geolocation object is used by the Google Maps API to display the geolocation information in the applications.
Code Snippet 6 demonstrates the code that displays current location of a user on the map using Geolocation object.
Code Snippet 6:

<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
html, body {
width: 100%;
height: 100%;
padding: 10%
}
#map_canvas {
height: 50%;
width: 50%;
}
</style>
<script src=”http://maps.google.com/maps/api/js?sensor=false”>
</script>
<script>
// Check support for Geolocation in the browser
if (navigator.geolocation) {
// Locate position and invoke function
navigator.geolocation.getCurrentPosition(displayPosition,
errorFunction);
} else {
alert(‘Geolocation is not enabled in your browser’);
}   
 
<body>
<div id=”map_canvas”></div>
<div id=”user_location”></div>
</body>
</html>    

The code uses the getCurrentPosition() method and retrieves the current position of the user. Then, it passes the information to displayPosition() function, which retrieves the coordinates, latitude and longitude. The retrieved coordinates are set into the properties of the Options object named myOptions and initialize the Map object. Finally, the Map object is displayed along with the current position information in the <div> element.
Drag Operation
HTML5 defines drag-and-drop operations that are based on events. The event-based mechanism allow the elements to be copied, reordered, or deleted on a Web page. The drag-and-drop operation involves the use of a pointing device, such as mouse on a visual medium. To perform the drag operation, a mousedown event is triggered followed by multiple mousemove events. Similarly, the drop operation is performed when a user releases the mouse.
The benefit of drag-and-drop mechanism is that it has brought the drag-and-drop operations on the browser level. This makes the programming easier, thus eliminating the need of complex JavaScript code written in earlier HTML versions.

<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop API</title>
</head>
<body>
<div id=”div” style=”border: red 2px solid; height:125px;
width:75px; padding: 10px”>
<img src=”image.jpg” height=”75” width=”75” id=”image1”
draggable=”true”/>
</div>
</body>
</html>    

Drag Events
During various stages of the drag-and-drop operation, a number of events are fired. These events are mouse-based events.

Events     Description       
dragstart     Triggers when an element is started to be dragged by the user       
drag     Triggers when an element is being dragged using a mouse       
dragleave     Triggers when the drag and drop operation is completed       
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Drag and Drop API</title>
<script>
function drag_image(event)
{
event.dataTransfer.setData(“image”, event.target.id);
}
</script>
</head>   


Drop Operation
After the element has been set up for dragging, it can be dropped on some element on the Web page. By default, elements on the page are not set up to receive dragged elements. Thus, the behavior of element acting as a drop element must be changed. This can be done by creating event listeners for the drop element. The drop element is also referred to as target element.
19.5.5 Drop Events
For any element to receive the drop operation, it must be associated with the drop events.

Event     Description       
dragenter     Triggers when a draggable element is being dragged on the target element for the first time       
dragleave     Triggers when an element is dragged outside the target element       
dragover     Triggers when an element is dragged inside the target element       
drop     Triggers when an element is dropped in the target element    
 
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Drag and Drop API</title>
<script>
function drag_image(event)
{
event.dataTransfer.setData(“image”, event.target.id);
}
function allow_drop(event)
{
event.preventDefault();
}
function drop_image(event)
{
var data=event.dataTransfer.getData(“image”);
event.target.appendChild(document.getElementById(data));



}
</script>
</head>
<body>
<div id=”div1” style=”border: blue 2px solid; height:125px;
width:75px; padding: 10px”>
<img src=”image.jpg” height=”75” width=”75” id=”image1”
draggable=”true” ondragstart=”drag_image(event)”/>
</div>
<br/>
<div id=”div2” style=”border: red 2px solid; height:125px;
width:75px; padding: 10px” ondrop=”drop_image(event)”
ondragover=”allow_drop(event)”>
</div>
</body>
</html>    
   


Offline Web Applications API
Consider a situation where a user is travelling outside the coverage area of Internet Service Provider (ISP). In this case, the user will not be able to access Web applications due to the network connection failure.
HTML5 supports offline Web applications that allow a user to work with them without being online. Offline Web applications work by saving all the Web pages locally on the user’s system. This feature is known as the Application Cache.
The Application Cache enables all resources, such as HTML, JavaScript, images, and CSS pages of an Web application to be stored locally on the system.
The following are the steps that can be taken to cache resources locally on the system:
Create a manifest file to define the resources that need to be saved.
Reference the manifest file in each Web page designed to use cached resources.
1. 2. 50 of 590 Concepts Session 19 HTML5 Geolocation and APIs V 1.1 © Zetutorials.blogspot.com  Limited
19.6.1 Creating a Manifest File
The manifest file is a text file that defines the caching behavior for resources used by the Web page. The file should be saved with the .manifest extension.
Code Snippet 10 demonstrates how to create a manifest file.
Code Snippet 10:

CACHE:
# Defines resources to be cached.
check.js
styles.css
images/figure1.jpg
FALLBACK:
# Defines resources to be used if non-cached resources cannot be #downloaded
Other_images/ figure2.png
NETWORK:
# Defines resources that will not be cached.    

HTML5 Geolocation and APIs
You will view and practice how to use new API in HTML5.
Working with Geolocation
and Google Maps APIs
             Working with the Drag and Drop API


                                                                                                                             Thank u
                                                                                                                 For watching  my website
                                                                                                                  Zetutorials.blogspot.com