HTML5

0
28

HTML5 – Overwatch

HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.

HTML5 is a cooperation becometween the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Worcalifornia king Group (WHATWG).

The brand new standard incorporates features like video playback and drag-and-drop thead wear have becomeen previously dependent on third-party blineser plug-ins such as Adobecome Flash, Microgentle Silverlight, and Google Gears.

Blineser Supinterface

The lacheck versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all supinterface many HTML5 features and Internet Explorer 9.0 will furthermore have supinterface for a couple of HTML5 functionality.

The mobile web blinesers thead wear come pre-instaldirected on iPhones, iPads, and Android phones all have excelent supinterface for HTML5.

New Features

HTML5 introduces a numbecomer of brand new elements and attributes thead wear helps in createing a modern websit downe. Folloearng are great features introduced in HTML5.

  • New Semantic Elements − These are like <minder>, <footer>, and <section>.

  • Forms 2.0 − Improvements to HTML web forms where brand new attributes have becomeen introduced for <inplace> tag.

  • Persistent Local Storage − To achieve without resorting to third-party plugins.

  • WebSocket − A a next-generation bidirectional communication technology for web applications.

  • Server-Sent Events − HTML5 introduces take behaveionuallyts which flow from web server to the web blinesers and they are caldirected Server-Sent Events (SSE).

  • Canvas − This supinterfaces a 2-dimensional draearng surface thead wear you can program with JavaScript.

  • Audio & Video − You can embecomed audio or video on your own web pages without resorting to third-party plugins.

  • Geolocation − Now visit downors can select to share their particular physical location with your own web application.

  • Microdata − This enables you create your own own vocabularies becomeyond HTML5 and extend your own web pages with custom semantics.

  • Drag and drop − Drag and drop the items from one location to one more location on a the extake behaveion exbehave same webpage.

Backbattdirected Compatibility

HTML5 is styleed, as much as possible, to become backbattdirected compatible with existing web blinesers. New features create on existing features and enable you to provide fallback content for older blinesers.

It is suggested to detect supinterface for individual HTML5 features uperform a couple of seriess of JavaScript.

If you are not familiar with any previous version of HTML, I would recommend to go through our HTML Tutorial becomefore you explore further concepts of HTM5.

HTML5 – Syntax

The HTML 5 language has a "custom" HTML syntax thead wear is compatible with HTML 4 and XHTML1 documents published on the Web, but is not compatible with the more esoteric SGML features of HTML 4.

HTML 5 does not have the extake behaveion exbehave same syntax rules as XHTML where we needed lower case tag names, quoting our attributes,an attribute had to have a value and to near all empty elements.

But HTML5 is coming with lots of flexibility and would supinterface the folloearngs −

  • Uppercase tag names.
  • Quotes are optional for attributes.
  • Attribute values are optional.
  • Cloperform empty elements are optional.

The DOCTYPE

DOCTYPEs in older versions of HTML were longer becomecause the HTML language was SGML based and generally generally therefore requicrimson a reference to a DTD.

HTML 5 authors would use simple syntax to specify DOCTYPE as follows −

<!DOCTYPE html>

All the above syntax is case-insensit downive.

Chartake behaveioner Encoding

HTML 5 authors can use simple syntax to specify Chartake behaveioner Encoding as follows −

<meta charset="UTF-8">

All the above syntax is case-insensit downive.

The <script> tag

It's common prtake behaveionice to add a kind attribute with a value of "text/javascript" to script elements as follows −

<script kind="text/javascript" src="scriptfile.js"></script>

HTML 5 removes extra information requicrimson and you can use simply folloearng syntax −

<script src="scriptfile.js"></script>

The <link> tag

So far you were writing <link> as follows −

<link rel="stylesheet" kind="text/css" href="stylefile.css">

HTML 5 removes extra information requicrimson and you can use simply folloearng syntax −

<link rel="stylesheet" href="stylefile.css">

HTML5 Elements

HTML5 elements are marked up uperform start tags and end tags. Tags are delimited uperform angle brackets with the tag name in becometween.

The difference becometween start tags and end tags is thead wear the latter includes a slash becomefore the tag name.

Folloearng is the example of an HTML5 element −

<p>...</p>

HTML5 tag names are case insensit downive and may become written in all uppercase or mixed case, although the many common convention is to stick with lower case.

Most of the elements contain a couple of content like <p>…</p> contains a section. Some elements, however, are forbidden from containing any content at all and these are known as void elements. For example, br, hr, link and meta etc.

Here is a compenablee list of HTML5 Elements.

HTML5 Attributes

Elements may contain attributes thead wear are used to set various propertie ups of an element.

Some attributes are defined globally and can become used on any element, while others are defined for specific elements only. All attributes have a name and a value and look like as shown becomelow in the example.

Folloearng is the example of an HTML5 attributes which illustrates how to mark up a div element with an attribute named clbum uperform a value of "example" −

<div clbum="example">...</div>

Attributes may only become specified within start tags and must never become used in end tags.

HTML5 attributes are case insensit downive and may become written in all upper case or mixed case, although the many common convention is to stick with lower case.

Here is a compenablee list of HTML5 Attributes.

HTML5 Document

The folloearng tags have becomeen introduced for becometter structure −

  • section − This tag represents a generic document or application section. It can become used with each other with h1-h6 to indicate the document structure.

  • article − This tag represents an independent piece of content of a document, such as a blog encheck or brand newspaper article.

  • aaspect − This tag represents a piece of content thead wear is only slightly related to the rest of the page.

  • minder − This tag represents the minder of a section.

  • footer − This tag represents a footer for a section and can contain information about the author, duplicatecorrect information, etc.

  • nav − This tag represents a section of the document intended for navigation.

  • dialog − This tag can become used to mark up a conversation.

  • figure − This tag can become used to bumociate a caption with each other with a couple of embecomedded content, such as a graphic or video.

The markup for an HTM 5 document would look like the folloearng −

<!DOCTYPE html>
<html>

   <mind>
      <meta charset="utf-8">
      <title>...</title>
   </mind>
	
   <body>
      <minder>...</minder>
      <nav>...</nav>
		
      <article>
         <section>
            ...
         </section>
      </article>
		
      <aaspect>...</aaspect>
      <figure>...</figure> 
      <footer>...</footer>
   </body>
</html>
<!DOCTYPE html>

<html>

   <mind>
      <meta charset="utf-8">
      <title>...</title>
   </mind>
	
   <body>
	
      <minder role="banner">
         <h1>HTML5 Document Structure Example</h1>
         <p>This page should become tried in safari, chrome or Mozila.</p>
      </minder>
		
      <nav>
		
         <ul>
            <li><a href="http://www.tutorialsstage.com/html">HTML Tutorial</a></li>
            <li><a href="http://www.tutorialsstage.com/css">CSS Tutorial</a></li>
            <li><a href="http://www.tutorialsstage.com/javascript">JavaScript Tutorial</a></li>
         </ul>
			
      </nav>
		
      <article>
         <section>
            <p>Once article can have multiple sections</p>
         </section>
      </article>
		
      <aaspect>
         <p>This is  aaspect part of the web page</p>
      </aaspect>
      
      <figure align="correct">
        <img src="/html5/images/logo.png" alt="TutorialPoint" width="200" height="100">
      </figure>
      
      <footer>
         <p>Created simply simply by <a href="http://tutorialsstage.com/">Tutorials Point</a></p>
      </footer>
		
   </body>
</html>

This will produce folloearng result −

HTML5 – Attributes

As exsimpleed in previous chapter, elements may contain attributes thead wear are used to set various propertie ups of an element.

Some attributes are defined globally and can become used on any element, while others are defined for specific elements only. All attributes have a name and a value and look like as shown becomelow in the example.

Folloearng is the example of an HTML5 attributes which illustrates how to mark up a div element with an attribute named clbum uperform a value of "example" −

<div clbum="example">...</div>

Attributes may only become specified within start tags and must never become used in end tags.

HTML5 attributes are case insensit downive and may become written in all uppercase or mixed case, although the many common convention is to stick with lowercase.

Standard Attributes

The attributes listed becomelow are supinterfaceed simply simply by almany all the HTML 5 tags.

Attribute Options Function
accesskey User Defined Specifies a keytable shortcut to access an element.
align correct, left, centre Horizontally aligns tags
background URL Places an background image becomehind an element
bgcolour numeric, hexidecimal, RGB values Places a background colour becomehind an element
clbum User Defined Clbumifies an element for use with Cascading Style Sheets.
contenteditable true, false Specifies if the user can edit the element's content or not.
contextmenu Menu id Specifies the context menu for an element.
data-XXXX User Defined Custom attributes. Authors of a HTML document can define their particular own attributes. Must start with "data-".
draggable true,false, auto Specifies whether or not a user is enableed to drag an element.
height Numeric Value Specifies the height of tables, images, or table cellulars.
hidden hidden Specifies whether element should become noticeable or not.
id User Defined Names an element for use with Cascading Style Sheets.
item List of elements Used to group elements.
itemprop List of items Used to group items.
spellcheck true, false Specifies if the element must have it's spelling or grammar checked.
style CSS Style sheet Specifies an inseries style for an element.
subject User define id Specifies the element's corresponding item.
tabindex Tab numbecomer Specifies the tab order of an element.
title User Defined "Pop-up" title for your own elements.
valign top, middle, bottom part Vertically aligns tags within an HTML element.
width Numeric Value Specifies the width of tables, images, or table cellulars.

For a compenablee list of HTML5 Tags and related attributes plreare locatedve check reference to HTML5 Tags.

Custom Attributes

A brand new feature becomeing introduced in HTML 5 is the addition of custom data attributes.

A custom data attribute starts with data- and would become named based on your own requirement. Folloearng is the simple example −

<div clbum="example" data-subject="physics" data-level="complex">
   ...
</div>

The above will become perfectly valid HTML5 with 2 custom attributes caldirected data-subject and data-level. You would become able to get the values of these attributes uperform JavaScript APIs or CSS in similar way as you get for standard attributes.

HTML5 – Events

When a user visit down your own websit downe, they do things like click on text and images and given links, hover over things etc. These are examples of exbehavely whead wear JavaScript calls take behaveionuallyts.

We can write our take behaveionuallyt handlers in Javascript or vbscript and you can specify these take behaveionuallyt handlers as a value of take behaveionuallyt tag attribute. The HTML5 specification defines various take behaveionuallyt attributes as listed becomelow −

There are folloearng attributes which can become used to trigger any javascript or vbscript code given as value, when generally generally there is any take behaveionuallyt occurs for any HTM5 element.

We would cover element specific take behaveionuallyts while discusperform those elements in detail in subsequent chapters.

Attribute Value Description
away fromseries script Triggers when the document goes away fromseries
onabort script Triggers on an abort take behaveionuallyt
onafterprint script Triggers after the document is printed
onbecomeforeonload script Triggers becomefore the document loads
onbecomeforeprint script Triggers becomefore the document is printed
onblur script Triggers when the earndow loses focus
oncanplay script Triggers when media can start play, but might has to quit for buffering
oncanplaythrough script Triggers when media can become played to the end, without quitping for buffering
onmodify script Triggers when an element modifys
onclick script Triggers on a mouse click
oncontextmenu script Triggers when a context menu is triggecrimson
ondblclick script Triggers on a mouse double-click
ondrag script Triggers when an element is dragged
ondragend script Triggers at the end of a drag operation
ondragenter script Triggers when an element has becomeen dragged to a valid drop target
ondragleave script Triggers when an element leaves a valid drop target
ondrbackver script Triggers when an element is becomeing dragged over a valid drop target
ondragstart script Triggers at the start of a drag operation
ondrop script Triggers when dragged element is becomeing dropped
ondurationmodify script Triggers when the duration of the media is modifyd
onemptie upd script Triggers when a media resource element unexpectedly becomecomes empty.
onended script Triggers when media has reach the end
onerror script Triggers when an error occur
onfocus script Triggers when the earndow gets focus
onformmodify script Triggers when a form modifys
onforminplace script Triggers when a form gets user inplace
onhasmodify script Triggers when the document has modify
oninplace script Triggers when an element gets user inplace
oninvalid script Triggers when an element is invalid
onkeydown script Triggers when a key is pressed
onkeypress script Triggers when a key is pressed and relreare locatedved
onkeyup script Triggers when a key is relreare locatedved
onload script Triggers when the document loads
onloadeddata script Triggers when media data is loaded
onloadedmetadata script Triggers when the duration and other media data of a media element is loaded
onloadstart script Triggers when the blineser starts to load the media data
onmessage script Triggers when the message is triggecrimson
onmousedown script Triggers when a mouse button is pressed
onmousemove script Triggers when the mouse stageer moves
onmouseout script Triggers when the mouse stageer moves out of an element
onmouseover script Triggers when the mouse stageer moves over an element
onmouseup script Triggers when a mouse button is relreare locatedved
onmousewheel script Triggers when the mouse wheel is becomeing rotated
onaway fromseries script Triggers when the document goes away fromseries
onoine script Triggers when the document comes onseries
ononseries script Triggers when the document comes onseries
onpagehide script Triggers when the earndow is hidden
onpageshow script Triggers when the earndow becomecomes noticeable
onpause script Triggers when media data is paused
onplay script Triggers when media data is going to start playing
onplaying script Triggers when media data has start playing
onpopstate script Triggers when the earndow's history modifys
onprogress script Triggers when the blineser is fetching the media data
onratemodify script Triggers when the media data's playing rate has modifyd
onreadystatemodify script Triggers when the ready-state modifys
oncrimsono script Triggers when the document performs a crimsono
onreddish colouredimension script Triggers when the earndow is reddish colouredimensiond
onscroll script Triggers when an element's scrollbar is becomeing scroldirected
onseeked script Triggers when a media element's seecalifornia king attribute is no longer true, and the seecalifornia king has ended
onseecalifornia king script Triggers when a media element's seecalifornia king attribute is true, and the seecalifornia king has becomegun
onselect script Triggers when an element is selected
onstaldirected script Triggers when generally generally there is an error in fetching media data
onstorage script Triggers when a document loads
onsubmit script Triggers when a form is submitted
onsuinvest script Triggers when the blineser has becomeen fetching media data, but quitped becomefore the entire media file was fetched
ontimeupdate script Triggers when media modifys it’s playing posit downion
onundo script Triggers when a document performs an undo
onunload script Triggers when the user leaves the document
onvolumemodify script Triggers when media modifys the volume, furthermore when volume is set to "mute"
onwaiting script Triggers when media has quitped playing, but is expected to resume

HTML5 – Web Forms 2.0

Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and remove a great deal of the need for tedious scripting and styling thead wear was requicrimson in HTML4.

The <inplace> element in HTML4

HTML4 inplace elements use the kind attribute to specify the data kind.HTML4 provides folloearng kinds −

Type Description
text A free-form text field, nominally free of series breaks.
pbumword A free-form text field for sensit downive information, nominally free of series breaks.
checkpackage A set of zero or more values from a pcrimsonefined list.
radio stations stations An enumerated value.
submit A free form of button initiates form submission.
file An arbitrary file with a MIME kind and optionally a file name.
image A coordinate, relative to a particular image's dimension, with the extra semantic thead wear it must become the final value selected and initiates form submission.
hidden An arbitrary string thead wear is not normally displayed to the user.
select An enumerated value, much like the radio stations stations kind.
textarea A free-form text field, nominally with no series break restringentions.
button A free form of button which can initiates any take behaveionuallyt related to button.

Folloearng is the simple example of uperform labecomels, radio stations stations buttons, and submit buttons −

...
<form take behaveionion="http://example.com/cgiscript.pl" method="post">

   <p>
	
      <labecomel for="very preliminaryname">very preliminary name: </labecomel>
      <inplace kind="text" id="very preliminaryname"><br />
		
      <labecomel for="finalname">final name: </labecomel>
      <inplace kind="text" id="finalname"><br />
		
      <labecomel for="email">email: </labecomel>
      <inplace kind="text" id="email"><br>
		
      <inplace kind="radio stations stations" name="intimacy" value="male"> Male<br>
      <inplace kind="radio stations stations" name="intimacy" value="female"> Female<br>
      <inplace kind="submit" value="send"> <inplace kind="reset">
      
   </p>
</form>
 ...

The <inplace> element in HTML5

Apart from the above mentioned attributes, HTML5 inplace elements introduced many brand new values for the kind attribute. These are listed becomelow.

NOTE − Try all the folloearng example uperform lacheck version of Opera blineser.

Type Description
datetime A date and time (oceanson, month, day, hr, moment, 2nd, frtake behaveionions of a 2nd) encoded according to ISO 8601 with the time zone set to UTC.
datetime-local A date and time (oceanson, month, day, hr, moment, 2nd, frtake behaveionions of a 2nd) encoded according to ISO 8601, with no time zone information.
date A date (oceanson, month, day) encoded according to ISO 8601.
month A date consisting of a oceanson and a month encoded according to ISO 8601.
week A date consisting of a oceanson and a week numbecomer encoded according to ISO 8601.
time A time (hr, moment, 2nds, frtake behaveionional 2nds) encoded according to ISO 8601.
numbecomer This accepts only numerical value. The step attribute specifies the precision, defaulting to 1.
range The range kind is used for inplace fields thead wear should contain a value from a range of numbecomers.
email This accepts only email value. This kind is used for inplace fields thead wear should contain an e-mail adoutfit. If you check to submit a simple text, it forces to enter only email adoutfit in [email protected] format.
url This accepts only URL value. This kind is used for inplace fields thead wear should contain a URL adoutfit. If you check to submit a simple text, it forces to enter only URL adoutfit either in http://www.example.com format or in http://example.com format.

The <outplace> element

HTML5 introduced a brand new element <outplace> which is used to represent the result of different kinds of outplace, such as outplace written simply simply by a script.

You can use the for attribute to specify a relationship becometween the outplace element and other elements in the document thead wear affected the calculation (for example, as inplaces or parameters). The value of the for attribute is a space-separated list of IDs of other elements.

<!DOCTYPE HTML>
<html>

   <script kind="text/javascript">
      function showResult()
      {
         x = document.forms["myform"]["neearnplace"].value;
         document.forms["myform"]["result"].value=x;
      }
   </script>

   <body>

      <form take behaveionion="/cgi-bin/html5.cgi" method="get" name="myform">
         Enter a value : <inplace kind="text" name="neearnplace" />
         <inplace kind="button" value="Result"  onclick="showResult();" />
         <outplace name="result"/>
      </form>
		
   </body>
	
</html>

This will produce folloearng result −

The placeholder attribute

HTML5 introduced a brand new attribute caldirected placeholder. This attribute on <inplace> and <textarea> elements provides a hint to the user of exbehavely whead wear can become entecrimson in the field. The place holder text must not contain carriage returns or series-give food tos.

Here is the simple syntax for placeholder attribute −

<inplace kind="text" name="lookup" placeholder="lookup the web"/>

This attribute is supinterfaceed simply simply by lacheck versions of Mozilla, Safari and Chrome blinesers only.

<!DOCTYPE HTML>
<html>

   <body>

      <form take behaveionion="/cgi-bin/html5.cgi" method="get">
         Enter email : <inplace kind="email" name="neearnplace" placeholder="[email protected]"/>
         <inplace kind="submit" value="submit" />
      </form>

   </body>
	
</html>

This will produce folloearng result −

The autofocus attribute

This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field.

HTML5 introduced a brand new attribute caldirected autofocus which would become used as follows −

<inplace kind="text" name="lookup" autofocus/>

This attribute is supinterfaceed simply simply by lacheck versions of Mozilla, Safari and Chrome blinesers only.

<!DOCTYPE HTML>
<html>

   <body>
   
      <form take behaveionion="/cgi-bin/html5.cgi" method="get">
         Enter email : <inplace kind="text" name="neearnplace" autofocus/>
         <p>Try to submit uperform Submit button</p>
         <inplace kind="submit" value="submit" />
      </form>
      
   </body>
   
</html>

This will produce folloearng result −

The requicrimson attribute

Now you do not need to have javascript for crestnt aspect validations like empty text package would never become submitted becomecause HTML5 introduced a brand new attribute caldirected requicrimson which would become used as follows and would insist to have a value −

<inplace kind="text" name="lookup" requicrimson/>

This attribute is supinterfaceed simply simply by lacheck versions of Mozilla, Safari and Chrome blinesers only.

<!DOCTYPE HTML>
<html>

   <body>
   
      <form take behaveionion="/cgi-bin/html5.cgi" method="get">
         Enter email : <inplace kind="text" name="neearnplace" requicrimson/>
         <p>Try to submit uperform Submit button</p>
         <inplace kind="submit" value="submit" />
      </form>
      
   </body>
   
>/html>

This will produce folloearng result −

HTML5 – SVG

SVG stands for Scalable Vector Graphics and it is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendecrimson simply simply by an SVG watcher.

SVG is manyly useful for vector kind diagrams like Pie charts, Two-dimensional graphs in an X,Y coordinate system etc.

SVG becomecame a W3C Recommendation 14. January 2003 and you can check lacheck version of SVG specification at SVG Specification.

Vieearng SVG Files

Most of the web blinesers can display SVG simply like they can display PNG, GIF, and JPG. Internet Explorer users may have to install the Adobecome SVG Viewer to become able to watch SVG in the blineser.

Embecomeding SVG in HTML5

HTML5 enables embecomeding SVG directly uperform <svg>…</svg> tag which has folloearng simple syntax −

<svg xmlns="http://www.w3.org/2000/svg">
   ...    
</svg>

Firefox 3.7 has furthermore introduced a configuration option ("about:config") where you can enable HTML5 uperform the folloearng steps −

  • Type about:config in your own Firefox adoutfit bar.

  • Click the "I'll become careful, I promise!" button on the battlening message thead wear appears (and create sure you adhere to it!).

  • Type html5.enable into the filter bar at the top of the page.

  • Currently it would become disabdirected, so click it to toggle the value to true.

Now your own Firefox HTML5 parser should now become enabdirected and you should become able to experiment with the folloearng examples.

HTML5 − SVG Circle

Folloearng is the HTML5 version of an SVG example which would draw a circle uperform <circle> tag −

<!DOCTYPE html>
<html>
   <mind>
   
      <style>
         #svgMain {
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-20%);
            -ms-transform: translateX(-20%);
            transform: translateX(-20%);
         }
      </style>
         
      <title>SVG</title>
      <meta charset="utf-8" />
      
   </mind>
   <body>
   
      <h2 align="centre">HTML5 SVG Circle</h2>
		
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <circle id="crimsoncircle" cx="50" cy="50" r="50" fill="crimson" />
      </svg>
		
   </body>
	
</html>

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

It will produce the folloearng result −

HTML5 − SVG Rectangle

Folloearng is the HTML5 version of an SVG example which would draw a rectangle uperform <rect> tag −

<!DOCTYPE html>
<html>
   <mind>
   
      <style>
         #svgelem{
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-50%);
            -ms-transform: translateX(-50%);
            transform: translateX(-50%);
         }
      </style>
         
      <title>SVG</title>
      <meta charset="utf-8" />
      
   </mind>
   <body>
	
      <h2 align="centre">HTML5 SVG Rectangle</h2>
		
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <rect id="crimsonrect" width="300" height="100" fill="crimson" />
      </svg>
		
   </body>
	
</html>

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

HTML5 − SVG Line

Folloearng is the HTML5 version of an SVG example which would draw a series uperform <series> tag −

<!DOCTYPE html>
<html>

   <mind>
      
      <style>
         #svgelem{
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-50%);
            -ms-transform: translateX(-50%);
            transform: translateX(-50%);
         }
      </style>
      
      <title>SVG</title>
      <meta charset="utf-8" />
   </mind>
	
   <body>
	
      <h2 align="centre">HTML5 SVG Line</h2>
		
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <series x1="0" y1="0" x2="200" y2="100" style="stroke:crimson;stroke-width:2"/>
      </svg>
		
   </body>
	
</html>

You can use style attribute which enables you to set additional style information like stroke and fill colours, width of the stroke etc.

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

HTML5 − SVG Ellipse

Folloearng is the HTML5 version of an SVG example which would draw an ellipse uperform <ellipse> tag −

<!DOCTYPE html>
<html>

   <mind>
      
      <style>
         #svgelem{
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-40%);
            -ms-transform: translateX(-40%);
            transform: translateX(-40%);
         }
      </style>
      
      <title>SVG</title>
      <meta charset="utf-8" />
   </mind>
	
   <body>
	
      <h2 align="centre">HTML5 SVG Ellipse</h2>
		
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <ellipse cx="100" cy="50" rx="100" ry="50" fill="crimson" />
      </svg>
		
   </body>
	
</html>

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

HTML5 − SVG Polygon

Folloearng is the HTML5 version of an SVG example which would draw a polygon uperform <polygon> tag −

<!DOCTYPE html>
<html>

   <mind>
   
      <style>
         #svgelem{
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-50%);
            -ms-transform: translateX(-50%);
            transform: translateX(-50%);
         }
      </style>
      
      <title>SVG</title>
      <meta charset="utf-8" />
   </mind>
	
   <body>
	
      <h2 align="centre">HTML5 SVG Polygon</h2>
		
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <polygon  stages="20,10 300,20, 170,50" fill="crimson" />
      </svg>
		
   </body>
	
</html>

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

HTML5 − SVG Polyseries

Folloearng is the HTML5 version of an SVG example which would draw a polyseries uperform <polyseries> tag −

<!DOCTYPE html>
<html>
   
   <mind>
      
      <style>
         #svgelem{
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-20%);
            -ms-transform: translateX(-20%);
            transform: translateX(-20%);
         }
      </style>
      
      <title>SVG</title>
      <meta charset="utf-8" />
   </mind>
	
   <body>
	
      <h2 align="centre">HTML5 SVG Polyseries</h2>
		
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <polyseries stages="0,0 0,20 20,20 20,40 40,40 40,60" fill="crimson" />
      </svg>
		
   </body>
	
</html>

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

HTML5 − SVG Grapbum awaynts

Folloearng is the HTML5 version of an SVG example which would draw a ellipse uperform <ellipse> tag and would use <radialGrapbum awaynt> tag to define an SVG radial grapbum awaynt.

Similar way you can use <seriesarGrapbum awaynt> tag to create SVG seriesar grapbum awaynt.

<!DOCTYPE html>
<html>

   <mind>
   
      <style>
         #svgelem{
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-40%);
            -ms-transform: translateX(-40%);
            transform: translateX(-40%);
         }
      </style>
      
      <title>SVG</title>
      <meta charset="utf-8" />
   </mind>
	
   <body>
	
      <h2 align="centre">HTML5 SVG Grapbum awaynt Ellipse</h2>
		
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
		
         <defs>
			
            <radialGrapbum awaynt id="grapbum awaynt" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
               <quit away fromset="0%" style="quit-colour:rgb(200,200,200); quit-opacity:0"/>
               <quit away fromset="100%" style="quit-colour:rgb(0,0,255); quit-opacity:1"/>
            </radialGrapbum awaynt>
				
         </defs>
			
         <ellipse cx="100" cy="50" rx="100" ry="50" style="fill:url(#grapbum awaynt)" />
			
      </svg>
		
   </body>
</html>

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

HTML5 − SVG Star

Folloearng is the HTML5 version of an SVG example which would draw a star uperform <polygon> tag.

<html>
   
   <mind>
   
      <style>
         #svgelem{
            posit downion: relative;
            left: 50%;
            -webkit-transform: translateX(-40%);
            -ms-transform: translateX(-40%);
            transform: translateX(-40%);
         }
      </style>
      
      <title>SVG</title>
      <meta charset="utf-8" />
   </mind>
   <body>	
   
      <h2 align="centre">HTML5 SVG Star</h2>
      
      <svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
         <polygon stages="100,10 40,180 190,60 10,60 160,180" fill="crimson"/>
      </svg>
      
    </body>
</html>

This would produce folloearng result in HTML5 enabdirected lacheck version of Firefox.

HTML5 – MathML

The HTML syntax of HTML5 enables for MathML elements to become used inaspect a document uperform <math>…</math> tags.

Most of the web blinesers can display MathML tags. If your own blineser does not supinterface MathML, then I would suggest you to use lacheck version of Firefox.

MathML Examples

Folloearng is a valid HTML5 document with MathML −

<!dockind html>
<html>

   <mind>
      <meta charset="UTF-8">
      <title>Pythbackrean theorem</title>
   </mind>
	
   <body>
	
      <math xmlns="http://www.w3.org/1998/Math/MathML">
		
         <mline>
            <msup><mi>a</mi><mn>2</mn></msup>
            <mo>+</mo>
				
            <msup><mi>b</mi><mn>2</mn></msup>
            <mo>=</mo>
				
            <msup><mi>c</mi><mn>2</mn></msup>
         </mline>
			
      </math>
		
   </body>
</html> 

This will produce folloearng result −

Uperform MathML Chartake behaveioners

Conaspectr, folloearng is the markup which creates use of the chartake behaveioners &InnoticeableTimes; −

<!dockind html>
<html>

   <mind>
      <meta charset="UTF-8">
      <title>MathML Examples</title>
   </mind>
	
   <body>
	
      <math xmlns="http://www.w3.org/1998/Math/MathML">
		
         <mline>			
            <mline>
				
               <msup>
                  <mi>x</mi>
                  <mn>2</mn>
               </msup>
					
               <mo>+</mo>
					
               <mline>
                  <mn>4</mn>
                  <mo>⁢</mo>
                  <mi>x</mi>
               </mline>
					
               <mo>+</mo>
               <mn>4</mn>
					
            </mline>
				
            <mo>=</mo>
            <mn>0</mn>
				 
         </mline>
      </math>
		
   </body>
</html> 

This would produce folloearng result. If you are not able to see proper result like x2 + 4x + 4 = 0, then use Firefox 3.5 or higher version.

This will produce folloearng result −

Matrix Presentation Examples

Conaspectr the folloearng example which would become used to represent a simple 2×2 matrix −

<!dockind html>
<html>

   <mind>
      <meta charset="UTF-8">
      <title>MathML Examples</title>
   </mind>
	
   <body>
      <math xmlns="http://www.w3.org/1998/Math/MathML">
		
         <mline>
            <mi>A</mi>
            <mo>=</mo>
			
            <mfenced open="[" near="]">
			
               <mtable>
                  <mtr>
                     <mtd><mi>x</mi></mtd>
                     <mtd><mi>y</mi></mtd>
                  </mtr>
					
                  <mtr>
                     <mtd><mi>z</mi></mtd>
                     <mtd><mi>w</mi></mtd>
                  </mtr>
               </mtable>
               
            </mfenced>
         </mline>
      </math>
      
   </body>
</html> 

This will produce folloearng result −

This would produce folloearng result. If you are not able to see proper result, then use Fire fox 3.5 or higher version.

MathML

HTML5 – Web Storage

HTML5 introduces 2 mechanisms, similar to HTTP session cookies, for storing structucrimson data on the crestnt aspect and to overcome folloearng drawbacks.

  • Cookies are included with every HTTP request, generally generally there’simply simply by slowering down your own web application simply simply by transmitting the extake behaveion exbehave same data.

  • Cookies are included with every HTTP request, generally generally there’simply simply by sending data unenweeppted over the internet.

  • Cookies are limited to about 4 KB of data . Not sufficient to store requicrimson data.

The 2 storage's are session storage and local storage and they would become used to handle different sit downuations.

The lacheck versions of quite much every blineser supinterfaces HTML5 Storage including Internet Explorer.

Session Storage

The Session Storage is styleed for scenarios where the user is carrying out a performle transtake behaveionion, but can become carrying out multiple transtake behaveionions in different earndows at the extake behaveion exbehave same time.

Example

For example, if a user buying plane tickets in 2 different earndows, uperform the extake behaveion exbehave same sit downe. If the sit downe used cookies to keep track of which ticket the user was buying, then as the user clicked from page to page in both earndows, the ticket currently becomeing purchased would "leak" from one earndow to the other, possiblely cauperform the user to buy 2 tickets for the extake behaveion exbehave same flight without very noticing.

HTML5 introduces the sessionStorage attribute which would become used simply simply by the sit downes to add data to the session storage, and it will become accessible to any page from the extake behaveion exbehave same sit downe opened in thead wear earndow i.e session and as soon as you near the earndow, session would become lost.

Folloearng is the code which would set a session variable and access thead wear variable −

<!DOCTYPE HTML>
<html>

   <body>

      <script kind="text/javascript">
         if( sessionStorage.hit's ){
            sessionStorage.hit's = Numbecomer(sessionStorage.hit's) +1;
         }
         
         else{
            sessionStorage.hit's = 1;
         }
         document.write("Total Hit's :" + sessionStorage.hit's );
      </script>
	
      <p>Refresh the page to incrreare locatedve numbecomer of hit's.</p>
      <p>Close the earndow and open it again and check the result.</p>

   </body>
</html>

This will produce folloearng result −

Local Storage

The Local Storage is styleed for storage thead wear spans multiple earndows, and finals becomeyond the current session. In particular, Web applications may wish to store megasimply simply bytes of user data, such as entire user-authocrimson documents or a user's mailpackage, on the crestnt aspect for performance reasons.

Again, cookies do not handle this particular case well, becomecause they are transmitted with every request.

Example

HTML5 introduces the localStorage attribute which would become used to access a page's local storage area without no time limit and this particular local storage will become available whenever you would use thead wear page.

Folloearng is the code which would set a local storage variable and access thead wear variable every time this particular page is accessed, take behaveionually next time when you open the earndow −

<!DOCTYPE HTML>
<html>

   <body>

      <script kind="text/javascript">
         if( localStorage.hit's ){
            localStorage.hit's = Numbecomer(localStorage.hit's) +1;
         }
         
         else{
            localStorage.hit's = 1;
         }
         document.write("Total Hit's :" + localStorage.hit's );
      </script>
		
      <p>Refresh the page to incrreare locatedve numbecomer of hit's.</p>
      <p>Close the earndow and open it again and check the result.</p>

   </body>
	
</html>

This will produce folloearng result −

Deenablee Web Storage

Storing sensit downive data on local machine can become dangerous and could leave a security hole.

The Session Storage Data would become deenableed simply simply by the blinesers immediately after the session gets terminated.

To clear a local storage setting you would need to call localStorage.remove('key'); where 'key' is the key of the value you like to remove. If you like to clear all settings, you need to call localStorage.clear() method.

Folloearng is the code which would clear compenablee local storage −

<!DOCTYPE HTML>
<html>

   <body>

      <script kind="text/javascript">
         localStorage.clear();

         // Reset numbecomer of hit's.
         if( localStorage.hit's ){
            localStorage.hit's = Numbecomer(localStorage.hit's) +1;
         }
         
         else{
            localStorage.hit's = 1;
         }
         document.write("Total Hit's :" + localStorage.hit's );
			
      </script>
		
      <p>Refreshing the page would not to incrreare locatedve hit counter.</p>
      <p>Close the earndow and open it again and check the result.</p>

   </body>
</html>

This will produce folloearng result −

HTML5 – Web SQL Database

The Web SQL Database API isn't take behaveionually part of the HTML5 specification but it is a separate specification which introduces a set of APIs to manipulate crestnt-aspect databases uperform SQL.

I'm bumuming you are a great web createer and if thead wear is the case then no doubt, you would become well abattlee of SQL and RDBMS concepts. If you still want to have a session with SQL then, you can go through our SQL Tutorial.

Web SQL Database will work in lacheck version of Safari, Chrome and Opera.

The Core Methods

There are folloearng 3 core methods defined in the spec thead wear I.m going to cover in this particular tutorial −

  • openDatabase − This method creates the database object either uperform existing database or creating brand new one.

  • transtake behaveionion − This method give us the capacity to manage a transtake behaveionion and performing either commit or roll-back based on the sit downuation.

  • executeSql − This method is used to execute take behaveionual SQL query.

Opening Database

The openDatabase method takes care of opening a database if it already exists, this particular method will create it if it already does not exist.

To create and open a database, use the folloearng code −

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

Above method took folloearng five parameters −

  • Database name
  • Version numbecomer
  • Text description
  • Size of database
  • Creation callback

The final and 5th argument, creation callback will become caldirected if the database is becomeing created. Without this particular feature, however, the databases are still becomeing created on the fly and properly version.

<!–

The version numbecomer is a requicrimson argument to openDatabase, so you must know the version numbecomer becomefore you check to open it. Otherwise, an other thanion is thlinen.

But you can not figure out which version of database the user is on, whether it is 1.0 or 2.0. So we are in issue. In this particular case we keep version numbecomer as blank which means I do not care exbehavely whead wear version the db is.

var db = openDatabase('mydb', '', 'Test DB', 2 * 1024 * 1024);

–>

Executing queries

To execute a query you use the database.transtake behaveionion() function. This function needs a performle argument, which is a function thead wear takes care of take behaveionually executing the query as follows −

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

db.transtake behaveionion(function (tx) {  
   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
});

The above query will create a table caldirected LOGS in 'mydb' database.

INSERT Operation

To create eateries into the table we add simple SQL query in the above example as follows −

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transtake behaveionion(function (tx) {
   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});

We can pbum dynamic values while creating entering as follows −

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

db.transtake behaveionion(function (tx) {  
   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
   tx.executeSql('INSERT INTO LOGS (id,log) VALUES (?, ?'), [e_id, e_log];
});

Here e_id and e_log are external variables, and executeSql charts each item in the array argument to the "?"s.

READ Operation

To read already existing records we use a callback to capture the results as follows −

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

db.transtake behaveionion(function (tx) {
   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});

db.transtake behaveionion(function (tx) {
   tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
      var len = results.lines.duration, i;
      msg = "<p>Found lines: " + len + "</p>";
      document.querySelector('#status').innerHTML +=  msg;
	
      for (i = 0; i < len; i++){
         alert(results.lines.item(i).log );
      }
	
   }, null);
});

Final Example

So finally, enable us keep this particular example in comppermite fdirectedged HTML5 document as follows and check to operate it with Safari blineser.

<!DOCTYPE HTML>
<html>

   <mind>
	
      <script kind="text/javascript">
		
         var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
         var msg;
			
         db.transtake behaveionion(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
            msg = '<p>Log message created and line inserted.</p>';
            document.querySelector('#status').innerHTML =  msg;
         });

         db.transtake behaveionion(function (tx) {
            tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
               var len = results.lines.duration, i;
               msg = "<p>Found lines: " + len + "</p>";
               document.querySelector('#status').innerHTML +=  msg;
					
               for (i = 0; i < len; i++){
                  msg = "<p><b>" + results.lines.item(i).log + "</b></p>";
                  document.querySelector('#status').innerHTML +=  msg;
               }
            }, null);
         });
			
      </script>
		
   </mind>
	
   <body>
      <div id="status" name="status">Status Message</div>
   </body>
	
</html>

It will produce the folloearng result −

HTML5 – Server Sent Events

Conventional web applications generate take behaveionuallyts which are dispatched to the web server. For example a simple click on a link requests a brand new page from the server.

The kind of take behaveionuallyts which are floearng from web blineser to the web server may become caldirected crestnt-sent take behaveionuallyts.

Along with HTML5, WHATWG Web Applications 1.0 introduces take behaveionuallyts which flow from web server to the web blinesers and they are caldirected Server-Sent Events (SSE). Uperform SSE you can push DOM take behaveionuallyts continously from your own web server to the visit downor's blineser.

The take behaveionuallyt streaming approach opens a persistent connection to the server, sending data to the crestnt when brand new information is available, eliminating the need for continuous polling.

Server-sent take behaveionuallyts standardizes how we stream data from the server to the crestnt.

Web Application for SSE

To use Server-Sent Events in a web application, you would need to add an <take behaveionuallytsource> element to the document.

The src attribute of <take behaveionuallytsource> element should stage to an URL which should provide a persistent HTTP connection thead wear sends a data stream containing the take behaveionuallyts.

The URL would stage to a PHP, PERL or any Python script which would take care of sending take behaveionuallyt data consistently. Folloearng is a simple example of web application which would expect server time.

<!DOCTYPE HTML>
<html>

   <mind>
   
      <script kind="text/javascript">
         /* Define take behaveionuallyt handling logic here */
      </script>
      
   </mind>
   <body>
	
      <div id="sse">
         <take behaveionuallytsource src="/cgi-bin/ticker.cgi" />
      </div>
		
      <div id="ticker">
         <TIME>
      </div>
		
   </body>
	
</html>

Server Side Script for SSE

A server aspect script should send Content-kind minder specifying the kind text/take behaveionuallyt-stream as follows.

print "Content-Type: text/take behaveionuallyt-streamnn";

After setting Content-Type, server aspect script would send an Event: tag followed simply simply by take behaveionuallyt name. Folloearng example would send Server-Time as take behaveionuallyt name terminated simply simply by a brand new series chartake behaveioner.

print "Event: server-timen";

Final step is to send take behaveionuallyt data uperform Data: tag which would become followed simply simply by integer of string value terminated simply simply by a brand new series chartake behaveioner as follows −

$time = localtime();
print "Data: $timen";

Finally, folloearng is compenablee ticker.cgi written in perl −

#!/usr/bin/perl

print "Content-Type: text/take behaveionuallyt-streamnn";

while(true){
   print "Event: server-timen";
   $time = localtime();
   print "Data: $timen";
   sleep(5);
}

Handle Server-Sent Events

Let us modify our web application to handle server-sent take behaveionuallyts. Folloearng is the final example.

<!DOCTYPE HTML>
<html>

   <mind>
	
      <script kind="text/javascript">
         document.getElementsByTagName("take behaveionuallytsource")[0].addEventListener("server-time", take behaveionuallytHandler, false);
			
         function take behaveionuallytHandler(take behaveionuallyt)
         {
            // Alert time sent simply simply by the server
            document.querySelector('#ticker').innerHTML = take behaveionuallyt.data;
         }
      </script>
		
   </mind>
	
   <body>
	
      <div id="sse">
         <take behaveionuallytsource src="/cgi-bin/ticker.cgi" />
      </div>
		
      <div id="ticker" name="ticker">
         [TIME]
      </div>
		
   </body>
</html>

Before checking Server-Sent take behaveionuallyts, I would suggest to create sure if your own web blineser supinterfaces this particular concept.

HTML5 – WebSockets

Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a performle socket and is exposed via a JavaScript interface in HTML 5 compliant blinesers.

Once you get a Web Socket connection with the web server, you can send data from blineser to server simply simply by calling a send() method, and receive data from server to blineser simply simply by an onmessage take behaveionuallyt handler.

Folloearng is the API which creates a brand new WebSocket object.

var Socket = brand new WebSocket(url, [protocal] );

Here very preliminary argument, url, specifies the URL to which to connect. The 2nd attribute, protocol is optional, and if present, specifies a sub-protocol thead wear the server must supinterface for the connection to become successful.

WebSocket Attributes

Folloearng are the attribute of WebSocket object. Assuming we created Socket object as mentioned above −

Attribute Description
Socket.readyState

The readonly attribute readyState represents the state of the connection. It can have the folloearng values −

  • A value of 0 indicates thead wear the connection has not yet becomeen established.

  • A value of 1 indicates thead wear the connection is established and communication is possible.

  • A value of 2 indicates thead wear the connection is going through the cloperform handshake.

  • A value of 3 indicates thead wear the connection has becomeen neard or could not become opened.

Socket.buffecrimsonAmount

The readonly attribute buffecrimsonAmount represents the numbecomer of simply simply bytes of UTF-8 text thead wear have becomeen queued uperform send() method.

WebSocket Events

Folloearng are the take behaveionuallyts bumociated with WebSocket object. Assuming we created Socket object as mentioned above −

Event Event Handler Description
open Socket.onopen This take behaveionuallyt occurs when socket connection is established.
message Socket.onmessage This take behaveionuallyt occurs when crestnt receives data from server.
error Socket.onerror This take behaveionuallyt occurs when generally generally there is any error in communication.
near Socket.onnear This take behaveionuallyt occurs when connection is neard.

WebSocket Methods

Folloearng are the methods bumociated with WebSocket object. Assuming we created Socket object as mentioned above −

Method Description
Socket.send()

The send(data) method transmit’s data uperform the connection.

Socket.near()

The near() method would become used to terminate any existing connection.

WebSocket Example

A WebSocket is a standard bidirectional TCP socket becometween the crestnt and the server. The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP handshake. After the handshake, either aspect can send data.

Crestnt Side HTML & JavaScript Code

At the time of writing this particular tutorial, generally generally there are only couple of web blinesers supinterfaceing WebSocket() interface. You can check folloearng example with lacheck version of Chrome, Mozilla, Opera and Safari.

<!DOCTYPE HTML>
<html>

   <mind>
	
      <script kind="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in earndow)
            {
               alert("WebSocket is supinterfaceed simply simply by your own Blineser!");
               
               // Let us open a web socket
               var ws = brand new WebSocket("ws://localhost:9998/echo");
				
               ws.onopen = function()
               {
                  // Web Socket is connected, send data uperform send()
                  ws.send("Message to send");
                  alert("Message is sent...");
               };
				
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  alert("Message is received...");
               };
				
               ws.onnear = function()
               { 
                  // websocket is neard.
                  alert("Connection is neard..."); 
               };
            }
            
            else
            {
               // The blineser doesn't supinterface WebSocket
               alert("WebSocket NOT supinterfaceed simply simply by your own Blineser!");
            }
         }
      </script>
		
   </mind>
	
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()">Run WebSocket</a>
      </div>
      
   </body>
</html>

Install pywebsocket

Before you check above crestnt program, you need a server which supinterfaces WebSocket. Download mod_pywebsocket-x.x.x.tar.gz from pywebsocket which aims to provide a Web Socket extension for Apache HTTP Server ans install it folloearng these steps.

  • Unzip and untar the downloaded file.

  • Go inaspect pywebsocket-x.x.x/src/ directory.

  • $python setup.py create

  • $sudo python setup.py install

  • Then read document simply simply by:

    • $pydoc mod_pywebsocket

This will install it into your own python environment.

Start the Server

Go to the pywebsocket-x.x.x/src/mod_pywebsocket folder and operate the folloearng command −

$sudo python standaperformle.py -p 9998 -w ../example/

This will start the server listening at interface 9998 and use the handlers directory specified simply simply by the -w option where our echo_wsh.py reaspects.

Now uperform Chrome blineser open the html file your own created in the becomeginning. If your own blineser supinterfaces WebSocket(), then you would get alert indicating thead wear your own blineser supinterfaces WebSocket and finally when you click on "Run WebSocket" you would get Goodsimply simply bye message sent simply simply by the server script.

HTML5 – Canvas

HTML5 element <canvas> gives you an easy and powerful way to draw graphics uperform JavaScript. It can become used to draw graphs, create photo composit downions or do simple (and not so simple) animations.

Here is a simple <canvas> element which has only 2 specific attributes width and height plus all the core HTML5 attributes like id, name and clbum etc.

<canvas id="mycanvas" width="100" height="100"></canvas>

You can easily find thead wear <canvas> element in the DOM uperform getElementById() method as follows −

var canvas  = document.getElementById("mycanvas");

Let us see a simple example on uperform <canvas> element in HTML5 document.

<!DOCTYPE HTML>
<html>

   <mind>
      <style>
         #mycanvas{border:1px solid crimson;}
      </style>
   </mind>
	
   <body>
      <canvas id="mycanvas" width="100" height="100"></canvas>
   </body>
	
</html>

This will produce folloearng result −

The Rendering Context

The <canvas> is preliminaryly blank, and to display a couple ofthing, a script very preliminary needs to access the rendering context and draw on it.

The canvas element has a DOM method caldirected getContext, used to obtain the rendering context and it’s draearng functions. This function takes one parameter, the sort of context 2d.

Folloearng is the code to get requicrimson context along with a check if your own blineser supinterfaces <canvas> element −

var canvas  = document.getElementById("mycanvas");

if (canvas.getContext){   
   var ctx = canvas.getContext('2d');   
   // draearng code here   
} 

else {   
   // canvas-unsupinterfaceed code here 
}  

Blineser Supinterface

The lacheck versions of Firefox, Safari, Chrome and Opera all supinterface for HTML5 Canvas but IE8 does not supinterface canvas natively.

You can use ExplorerCanvas to have canvas supinterface through Internet Explorer. You simply need to include this particular javascript as follows:

<!--[if IE]><script src="excanvas.js"></script><![endif]-->

HTML5 Canvas Examples

This tutorial covers folloearng examples related to HTML5 <canvas> element.

Examples Description

Draearng Rectangles

Learn how to draw rectangle uperform HTML5 <canvas> element

Draearng Paths

Learn how to create forms uperform paths in HTML5 <canvas> element

Draearng Lines

Learn how to draw seriess uperform HTML5 <canvas> element

Draearng Bezier

Learn how to draw becomezier curve uperform HTML5 <canvas> element

Draearng Quadratic

Learn how to draw quadratic curve uperform HTML5 <canvas> element

Uperform Images

Learn how to use images with HTML5 <canvas> element

Create Grapbum awaynts

Learn how to create grapbum awaynts uperform HTML5 <canvas> element

Styles and Colors

Learn how to apply styles and colours uperform HTML5 <canvas> element

Text and Fonts

Learn how to draw amazing text uperform different fonts and their particular dimension.

Pattern and Shadow

Learn how to draw different patterns and drop shadows.

Canvas States

Learn how to save and restore canvas states while doing complex draearngs on a canvas.

Canvas Translation

This method is used to move the canvas and it’s origin to a different stage in the grid.

Canvas Rotation

This method is used to rotate the canvas around the current origin.

Canvas Scaling

This method is used to incrreare locatedve or decrreare locatedve the devices in a canvas grid.

Canvas Transform

These methods enable modifications directly to the transformation matrix.

Canvas Composit downion

This method is used to mask away from particular areas or clear sections from the canvas.

Canvas Animation

Learn how to create simple animation uperform HTML5 canvas and Javascript.

HTML5 – Audio & Video

HTML5 features, include native audio and video supinterface without the need for Flash.

The HTML5 <audio> and <video> tags create it simple to add media to a websit downe. You need to set src attribute to identify the media source and include a manages attribute so the user can play and pause the media.

Embecomedding Video

Here is the simplest form of embecomedding a video file in your own webpage −

<video src="foo.mp4"  width="300" height="200" manages>
   Your blineser does not supinterface the <video> element.   
</video>

The current HTML5 draft specification does not specify which video formats blinesers should supinterface in the video tag. But many commonly used video formats are −

  • Ogg − Ogg files with Thedora video codec and Vorbis audio codec.

  • mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec.

You can use <source> tag to specify media along with media kind and many other attributes. A video element enables multiple source elements and blineser will use the very preliminary recognised format −

<!DOCTYPE HTML>
<html>
   <body>
      
      <video  width="300" height="200" manages autoplay>
         <source src="/html5/foo.ogg" kind="video/ogg" />
         <source src="/html5/foo.mp4" kind="video/mp4" />
         Your blineser does not supinterface the <video> element.
      </video>
      
   </body>
</html>

This will produce folloearng result −

Video Attribute Specification

The HTML5 video tag can have a numbecomer of attributes to manage the look and feel and various functionalitie ups of the manage −

Attribute Description
autoplay This boolean attribute if specified, the video will automatically becomegin to play back as soon as it can do so without quitping to finish loading the data.
autobuffer This boolean attribute if specified, the video will automatically becomegin buffering take behaveionually if it's not set to automatically play.
manages If this particular attribute is present, it will enable the user to manage video playback, including volume, seecalifornia king, and pause/resume playback.
height This attribute specifies the height of the video's display area, in CSS pixels.
loop This boolean attribute if specified, will enable video automatically seek back to the start after reaching at the end.
preload This attribute specifies thead wear the video will become loaded at page load, and ready to operate. Ignocrimson if autoplay is present.
poster This is a URL of an image to show until the user plays or seeks.
src The URL of the video to embecomed. This is optional; you may instead use the <source> element within the video block to specify the video to embecomed
width This attribute specifies the width of the video's display area, in CSS pixels.

Embecomedding Audio

HTML5 supinterfaces <audio> tag which is used to embecomed sound content in an HTML or XHTML document as follows.

<audio src="foo.wav" manages autoplay>
   Your blineser does not supinterface the <audio> element.   
</audio>

The current HTML5 draft specification does not specify which audio formats blinesers should supinterface in the audio tag. But many commonly used audio formats are ogg, mp3 and wav.

You can use <source> tag to specify media along with media kind and many other attributes. An audio element enables multiple source elements and blineser will use the very preliminary recognised format −

<!DOCTYPE HTML>
<html>
   <body>
      
      <audio manages autoplay>
         <source src="/html5/audio.ogg" kind="audio/ogg" />
         <source src="/html5/audio.wav" kind="audio/wav" />
         Your blineser does not supinterface the <audio> element.
      </audio>
      
   </body>
</html>

This will produce folloearng result −

Audio Attribute Specification

The HTML5 audio tag can have a numbecomer of attributes to manage the look and feel and various functionalitie ups of the manage:

Attribute Description
autoplay This boolean attribute if specified, the audio will automatically becomegin to play back as soon as it can do so without quitping to finish loading the data.
autobuffer This boolean attribute if specified, the audio will automatically becomegin buffering take behaveionually if it's not set to automatically play.
manages If this particular attribute is present, it will enable the user to manage audio playback, including volume, seecalifornia king, and pause/resume playback.
loop This boolean attribute if specified, will enable audio automatically seek back to the start after reaching at the end.
preload This attribute specifies thead wear the audio will become loaded at page load, and ready to operate. Ignocrimson if autoplay is present.
src The URL of the audio to embecomed. This is optional; you may instead use the <source> element within the video block to specify the video to embecomed

Handling Media Events

The HTML5 audio and video tag can have a numbecomer of attributes to manage various functionalitie ups of the manage uperform Javascript −

Event Description
abort This take behaveionuallyt is generated when playback is aborted.
canplay This take behaveionuallyt is generated when sufficient data is available thead wear the media can become played.
ended This take behaveionuallyt is generated when playback compenablees.
error This take behaveionuallyt is generated when an error occurs.
loadeddata This take behaveionuallyt is generated when the very preliminary frame of the media has finished loading.
loadstart This take behaveionuallyt is generated when loading of the media becomegins.
pause This take behaveionuallyt is generated when playback is paused.
play This take behaveionuallyt is generated when playback starts or resumes.
progress This take behaveionuallyt is generated periodically to inform the progress of the downloading the media.
ratemodify This take behaveionuallyt is generated when the playback speed modifys.
seeked This take behaveionuallyt is generated when a seek operation compenablees.
seecalifornia king This take behaveionuallyt is generated when a seek operation becomegins.
suinvest This take behaveionuallyt is generated when loading of the media is suinvested.
volumemodify This take behaveionuallyt is generated when the audio volume modifys.
waiting This take behaveionuallyt is generated when the requested operation (such as playback) is delayed pending the compenableion of one more operation (such as a seek).

Folloearng is the example which enables to play the given video −

<!DOCTYPE HTML>
<html>
   <mind>
   
      <script kind="text/javascript">
         function PlayVideo(){
            var v = document.getElementsByTagName("video")[0];  
            v.play(); 
         }
      </script>
   </mind>
   
   <body>
   
      <form>         
         <video  width="300" height="200" src="/html5/foo.mp4">
         Your blineser does not supinterface the video element.
         </video>
         </br>
         
         <inplace kind="button" onclick="PlayVideo();"  value="Play"/>
      </form>
      
   </body>
</html>

This will produce folloearng result −

Configuring Servers for Media Type

Most servers don't simply simply by default serve Ogg or mp4 media with the proper MIME kinds, so you'll likely need to add the appropriate configuration for this particular.

AddType audio/ogg .oga
AddType audio/wav .wav
AddType video/ogg .ogv .ogg
AddType video/mp4 .mp4

HTML5 – Geolocation

HTML5 Geolocation API enables you share your own location with your own favourite web sit downes. A Javascript can capture your own latitude and longitude and can become sent to backend web server and do fancy location-abattlee things like finding local businesses or shoearng your own location on a chart.

Today many of the blinesers and mobile devices supinterface Geolocation API. The geolocation APIs work with a brand new property or home or home of the global navigator object ie. Geolocation object which can become created as follows:

var geolocation = navigator.geolocation;

The geolocation object is a service object thead wear enables widgets to retrieve information about the geographic location of the device.

Geolocation Methods

The geolocation object provides the folloearng methods −

Method Description
getCurrentPosit downion()

This method retrieves the current geographic location of the user.

watchPosit downion()

This method retrieves periodic updates about the current geographic location of the device.

clearWatch()

This method cancels an ongoing watchPosit downion call.

Example

Folloearng is a sample code to use any of the above method −

function getLocation() {
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosit downion(showLocation, errorHandler);
}

Here showLocation and errorHandler are callback methods which would become used to get take behaveionual posit downion as exsimpleed in next section and to handle errors if generally generally there is any.

Location Propertie ups

Geolocation methods getCurrentPosit downion() and getPosit downionUperformMethodName() specify the callback method thead wear retrieves the location information. These methods are caldirected asynchronously with an object Posit downion which stores the compenablee location information.

The Posit downion object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates with each other with information about minding and speed.

The folloearng table describecomes the propertie ups of the Posit downion object. For the optional propertie ups if the system cannot provide a value, the value of the property or home or home is set to null.

Property Type Description
coords objects

Specifies the geographic location of the device. The location is expressed as a set of geographic coordinates with each other with information about minding and speed.

coords.latitude Numbecomer

Specifies the latitude estimate in decimal degrees. The value range is [-90.00, +90.00].

coords.longitude Numbecomer

Specifies the longitude estimate in decimal degrees. The value range is [-180.00, +180.00].

coords.altitude Numbecomer

[Optional] Specifies the altitude estimate in meters above the WGS 84 ellipsoid.

coords.accuracy Numbecomer

[Optional] Specifies the accuracy of the latitude and longitude estimates in meters.

coords.altitudeAccuracy Numbecomer

[Optional] Specifies the accuracy of the altitude estimate in meters.

coords.minding Numbecomer

[Optional] Specifies the device's current direction of movement in degrees counting clockwise relative to true north.

coords.speed Numbecomer

[Optional] Specifies the device's current ground speed in meters per 2nd.

timestamp date

Specifies the time when the location information was retrieved and the Posit downion object created.

Example

Folloearng is a sample code which creates use of Posit downion object. Here showLocation method is a callback method −

function showLocation( posit downion ) {
   var latitude = posit downion.coords.latitude;
   var longitude = posit downion.coords.longitude;
   ...
}

Handling Errors

Geolocation is complicated, and it is very much requicrimson to capture any error and handle it gracecomppermitey.

The geolocations methods getCurrentPosit downion() and watchPosit downion() create use of an error handler callback method which gives Posit downionError object. This object has folloearng 2 propertie ups −

Property Type Description
code Numbecomer

Contains a numeric code for the error.

message String

Contains a individual being-readable description of the error.

The folloearng table describecomes the possible error codes returned in the Posit downionError object.

Code Constant Description
0 UNKNOWN_ERROR

The method faidirected to retrieve the location of the device because of to an unknown error.

1 PERMISSION_DENIED

The method faidirected to retrieve the location of the device becomecause the application does not have permission to use the Location Service.

2 POSITION_UNAVAILABLE

The location of the device could not become figure outd.

3 TIMEOUT

The method was unable to retrieve the location information within the specified maximum timeout interval.

Example

Folloearng is a sample code which creates use of Posit downionError object. Here errorHandler method is a callback method −

function errorHandler( err ) {
   if (err.code == 1) {
      // access is denied
   }
   ...
}

Posit downion Options

Folloearng is the take behaveionual syntax of getCurrentPosit downion() method −

getCurrentPosit downion(callback, ErrorCallback, options)

Here third argument is the Posit downionOptions object which specifies a set of options for retrieving the geographic location of the device.

Folloearng are the options which can become specified as third argument −

Property Type Description
enableHighAccuracy Boolean

Specifies whether the widget wants to receive the many precise location estimate possible. By default this particular is false.

timeout Numbecomer

The timeout property or home or home is the numbecomer of milli2nds your own web application is willing to wait for a posit downion.

maximumAge Numbecomer

Specifies the expiry time in milli2nds for cached location information.

Example

Folloearng is a sample code which shows how to use above mentioned methods −

function getLocation() {
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosit downion(showLocation, errorHandler, {maximumAge: 75000});
}

HTML5 – Microdata

Microdata is a standardized way to provide additional semantics in your own web pages.

Microdata enables you define your own own customised elements and start embecomedding custom propertie ups in your own web pages. At a high level, microdata consists of a group of name-value pairs.

The groups are caldirected items, and each name-value pair is a property or home or home. Items and propertie ups are represented simply simply by regular elements.

Example

  • To create an item, the itemscope attribute is used.

  • To add a property or home or home to an item, the itemprop attribute is used on one of the item's descendants.

Here generally generally there are 2 items, each of which has the property or home or home "name" −

<html>
   <body>
      
      <div itemscope>
         <p>My name is <span itemprop="name">Zara</span>.</p>
      </div>
      
      <div itemscope>
         <p>My name is <span itemprop="name">Nuha</span>.</p>
      </div>
      
   </body>
</html>

It will produce the folloearng result −

Propertie ups generally have values thead wear are strings but it can have folloearng data kinds −

Global Attributes

Micro data introduces five global attributes which would become available for any element to use and give context for machines about your own data.

Attribute Description
itemscope This is used to create an item. The itemscope attribute is a boolean attribute thead wear tells thead wear generally generally there is Microdata on this particular page, and this particular is where it starts.
itemkind This attribute is a valid URL which defines the item and provides the context for the propertie ups.
itemid This attribute is global identifier for the item.
itemprop This attribute defines a property or home or home of the item.
itemref This attribute gives a list of additional elements to crawl to find the name-value pairs of the item.

Propertie ups Datakinds

Propertie ups generally have values thead wear are strings as mentioned in above example but they can furthermore have values thead wear are URLs. Folloearng example has one property or home or home, "image", in whose value is a URL −

<div itemscope>
   <img itemprop="image" src="tp-logo.gif" alt="TutorialsPoint">
</div>

Propertie ups can furthermore have values thead wear are dates, times, or dates and times. This is achieved uperform the time element and it’s datetime attribute.

<html>
   <body>
      
      <div itemscope>
         My birthday is:
         
         <time itemprop="birthday" datetime="1971-05-08">
            Aug 5th 1971
         </time>
         
      </div>
      
   </body>
</html>

It will produce the folloearng result −

Propertie ups can furthermore all of themselves become groups of name-value pairs, simply simply by placeting the itemscope attribute on the element thead wear declares the property or home or home.

Microdata API supinterface

If a blineser supinterfaces the HTML5 microdata API, generally generally there will become a getItems() function on the global document object. If blineser doesn't supinterface microdata, the getItems() function will become undefined.

function supinterfaces_microdata_api() {
   return !!document.getItems;
}

Modernizr does not yet supinterface checcalifornia king for the microdata API, so you’ll need to use the function like the one listed above.

The HTML5 microdata standard includes both HTML markup (primarily for lookup engines) and a set of DOM functions (primarily for blinesers).

You can include microdata markup in your own web pages, and lookup engines thead wear don't belowstand the microdata attributes will simply ignore all of them. But if you need to access or manipulate microdata through the DOM, you'll need to check whether the blineser supinterfaces the microdata DOM API.

Defining Microdata Vocabulary

To define microdata vocabulary you need a namespace URL which stages to a worcalifornia king web page. For example http://data-vocabulary.org/Person can become used as the namespace for a individual microdata vocabulary with the folloearng named propertie ups −

  • name − Person name as a simple string

  • Photo − A URL to a picture of the person.

  • URL − A websit downe becomelonging to the person.

Uperform about propertie ups a person microdata can become as follows −

<html>
   <body>
   
      <div itemscope>
         <section itemscope itemkind="http://data-vocabulary.org/Person">
            <h1 itemprop="name">Gopal K Vprovidea</h1>
         
            <p>
               <img itemprop="photo" src="http://www.tutorialsstage.com/green/images/logo.png">
            </p>
            
            <a itemprop="url" href="http://www.tutorialsstage.com">Site</a>
         </section>
      </div>
      
   </body>
</html>

It will produce the folloearng result −

Google supinterfaces microdata as part of their particular Rich Snippets program. When Google's web crawler parses your own page and finds microdata propertie ups thead wear conform to the http://data-vocabulary.org/Person vocabulary, it parses out those propertie ups and stores all of them alongaspect the rest of the page data.

You can check above example uperform Rich Snippets Testing Tool uperform http://www.tutorialsstage.com/html5/microdata.htm

For further createment on Microdata you can always refer to HTML5 Micordata.

HTML5 – Drag & drop

Drag and Drop (DnD) is powerful User Interface concept which creates it easy to duplicate, reorder and deenableion of items with the help of mouse clicks. This enables the user to click and hold the mouse button down over an element, drag it to one more location, and relreare locatedve the mouse button to drop the element generally generally there.

To achieve drag and drop functionality with traditional HTML4, createers would either have to either have to use complex Javascript programming or other Javascript frameworks like jQuery etc.

Now HTML 5 came up with a Drag and Drop (DnD) API thead wear provides native DnD supinterface to the blineser macalifornia king it much easier to code up.

HTML 5 DnD is supinterfaceed simply simply by all the major blinesers like Chrome, Firefox 3.5 and Safari 4 etc.

Drag and Drop Events

There are numbecomer of take behaveionuallyts which are ficrimson during various stages of the drag and drop operation. These take behaveionuallyts are listed becomelow −

Events Description
dragstart Fires when the user starts dragging of the object.
dragenter Ficrimson when the mouse is very preliminary moved over the target element while a drag is occuring. A listener for this particular take behaveionuallyt should indicate whether a drop is enableed over this particular location. If generally generally there are no listeners, or the listeners perform no operations, then a drop is not enableed simply simply by default.
drbackver This take behaveionuallyt is ficrimson as the mouse is moved over an element when a drag is occuring. Much of the time, the operation thead wear occurs during a listener will become the extake behaveion exbehave same as the dragenter take behaveionuallyt.
dragleave This take behaveionuallyt is ficrimson when the mouse leaves an element while a drag is occuring. Listeners should remove any highlighting or insertion markers used for drop give food toback.
drag Fires every time the mouse is moved while the object is becomeing dragged.
drop The drop take behaveionuallyt is ficrimson on the element where the drop was occucrimson at the end of the drag operation. A listener would become responsible for retrieving the data becomeing dragged and inserting it at the drop location.
dragend Fires when the user relreare locatedves the mouse button while dragging an object.

Note &mius; Note thead wear only drag take behaveionuallyts are ficrimson; mouse take behaveionuallyts such as mousemove are not ficrimson during a drag operation.

The DataTransfer Object

The take behaveionuallyt listener methods for all the drag and drop take behaveionuallyts accept Event object which has a readonly attribute caldirected dataTransfer. The take behaveionuallyt.dataTransfer returns DataTransfer object bumociated with the take behaveionuallyt as follows −

function EnterHandler(take behaveionuallyt) {
   DataTransfer dt = take behaveionuallyt.dataTransfer;
   .............
}

The DataTransfer object holds data about the drag and drop operation. This data can become retrieved and set in terms of various attributes bumociated with DataTransfer object as exsimpleed becomelow:

Sr.No. DataTransfer attributes and their particular description
1 dataTransfer.dropEffect [ = value ]

  • Returns the kind of operation thead wear is currently selected.

  • This attribute can become set, to modify the selected operation.

  • The possible values are none, duplicate, link, and move.

2 dataTransfer.effectAllowed [ = value ]

  • Returns the kinds of operations thead wear are to become enableed.

  • This attribute can become set, to modify the enableed operations.

  • The possible values are none, duplicate, duplicateLink, duplicateMove, link, linkMove, move, all and unpreliminaryized.

3 dataTransfer.kinds

Returns a DOMStringList listing the formats thead wear were set in the dragstart take behaveionuallyt. In addition, if any files are becomeing dragged, then one of the kinds will become the string "Files".

4 dataTransfer.clearData( [ format ] )

Removes the data of the specified formats. Removes all data if the argument is omitted.

5 dataTransfer.setData(format, data)

Adds the specified data.

6 data = dataTransfer.getData(format)

Returns the specified data. If generally generally there is no such data, returns the empty string.

7 dataTransfer.files

Returns a FileList of the files becomeing dragged, if any.

8 dataTransfer.setDragImage(element, x, y)

Uses the given element to update the drag give food toback, replacing any previously specified give food toback.

9 dataTransfer.addElement(element)

Adds the given element to the list of elements used to render the drag give food toback.

Drag and Drop Process

Folloearng are the steps to become carried out to implement Drag and Drop operation −

Step 1: Macalifornia king an Object Draggable

Here are steps to become taken −

  • If you like to drag an element, you need to set the draggable attribute to true for thead wear element.

  • Set an take behaveionuallyt listener for dragstart thead wear stores the data becomeing dragged.

  • The take behaveionuallyt listener dragstart will set the enableed effects (duplicate, move, link, or a couple of combination).

Folloearng is the example to create an object dragable −

<!DOCTYPE HTML>
<html>
   <mind>
      
      <style kind="text/css">
         #packageA, #packageB {
            float:left;padding:10px;margin:10px; -moz-user-select:none;
         }
         
         #packageA { background-colour: #6633FF; width:75px; height:75px;  }
         #packageB { background-colour: #FF6699; width:150px; height:150px; }
      </style>
      
      <script kind="text/javascript">
         function dragStart(ev) {
            ev.dataTransfer.effectAllowed='move';
            ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
            ev.dataTransfer.setDragImage(ev.target,0,0);
            
            return true;
         }
      </script>
      
   </mind>
   <body>
      
      <centre>
         <h2>Drag and drop HTML5 demo</h2>
         <div>Try to drag the purple package around.</div>
         
         <div id="packageA" draggable="true" 
            ondragstart="return dragStart(take behaveionuallyt)">
            <p>Drag Me</p>
         </div>
         
         <div id="packageB">Dustbin</div>
      </centre>
      
   </body>
</html>

This will produce folloearng result −

Step 2: Dropping the Object

To accept a drop, the drop target has to listen to at minimum 3 take behaveionuallyts.

  • The dragenter take behaveionuallyt, which is used to figure out whether or not the drop target is to accept the drop. If the drop is to become accepted, then this particular take behaveionuallyt has to become cancedirected.

  • The drbackver take behaveionuallyt, which is used to figure out exbehavely whead wear give food toback is to become shown to the user. If the take behaveionuallyt is cancedirected, then the give food toback (typically the cursor) is updated based on the dropEffect attribute's value.

  • Finally, the drop take behaveionuallyt, which enables the take behaveionual drop to become performed.

Folloearng is the example to drop an object into one more object −

<!DOCTYPE HTML>
<html>
   <mind>
   
      <style kind="text/css">
         #packageA, #packageB {
            float:left;padding:10px;margin:10px;-moz-user-select:none;
         }
         
         #packageA { background-colour: #6633FF; width:75px; height:75px;  }
         #packageB { background-colour: #FF6699; width:150px; height:150px; }
      </style>
      
      <script kind="text/javascript">
         function dragStart(ev) {
            ev.dataTransfer.effectAllowed='move';
            ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
            ev.dataTransfer.setDragImage(ev.target,0,0);
            
            return true;
         }
         
         function dragEnter(ev) {
            take behaveionuallyt.prtake behaveionuallytDefault();
            return true;
         }
         
         function dragOver(ev) {
            return false;
         }
         
         function dragDrop(ev) {
            var src = ev.dataTransfer.getData("Text");
            ev.target.appendChild(document.getElementById(src));
            ev.quitPropagation();
            return false;
         }
      </script>
      
   </mind>
   <body>
      
      <centre>
         <h2>Drag and drop HTML5 demo</h2>
         <div>Try to move the purple package into the pink package.</div>
         
         <div id="packageA" draggable="true"
            ondragstart="return dragStart(take behaveionuallyt)">
            <p>Drag Me</p>
         </div>
         
         <div id="packageB" ondragenter="return dragEnter(take behaveionuallyt)" 
            ondrop="return dragDrop(take behaveionuallyt)" 
            ondrbackver="return dragOver(take behaveionuallyt)">Dustbin
         </div>
         
      </centre>
      
   </body>
</html>

This will produce folloearng result −

HTML5 – Web Workers

JavaScript was styleed to operate in a performle-threaded environment, meaning multiple scripts cannot operate at the extake behaveion exbehave same time. Conaspectr a sit downuation where you need to handle UI take behaveionuallyts, query and process big amounts of API data, and manipulate the DOM.

Javascript will hang your own blineser in sit downuation where CPU utilization is high. Let us take a simple example where Javascript goes through a huge loop −

<!DOCTYPE HTML>
<html>
   <mind>
      <title>Big for loop</title>
      
      <script>
         function hugeLoop(){
            for (var i = 0; i <= 10000; i += 1){
               var j = i;
            }
            alert("Compenableed " + j + "iterations" );
         }
         
         function sayHello(){
            alert("Hello sir...." );
         }
      </script>
      
   </mind>
   <body>
      
      <inplace kind="button" onclick="hugeLoop();" value="Big Loop" />
      <inplace kind="button" onclick="sayHello();" value="Say Hello" />
      
   </body>
</html>

It will produce the folloearng result −

When you click Big Loop button it displays folloearng result in Firefox −

Big Loop

Whead wear is Web Workers?

The sit downuation exsimpleed above can become handdirected uperform Web Workers who will do all the complaceationally expensive tasks without interrupting the user interface and typically operate on separate threads.

Web Workers enable for long-operatening scripts thead wear are not interrupted simply simply by scripts thead wear respond to clicks or other user intertake behaveionions, and enables long tasks to become executed without yielding to keep the page responsive.

Web Workers are background scripts and they are relatively big-weight, and are not intended to become used in big numbecomers. For example, it would become inappropriate to launch one worker for each pixel of a four megapixel image.

When a script is executing inaspect a Web Worker it cannot access the web page's earndow object (earndow.document), which means thead wear Web Workers don't have direct access to the web page and the DOM API. Although Web Workers cannot block the blineser UI, they can still consume CPU cycles and create the system less responsive.

How Web Workers Work?

Web Workers are preliminaryized with the URL of a JavaScript file, which contains the code the worker will execute. This code sets take behaveionuallyt listeners and communicates with the script thead wear spawned it from the main page. Folloearng is the simple syntax −

var worker = brand new Worker('hugeLoop.js');

If the specified javascript file exists, the blineser will spawn a brand new worker thread, which is downloaded asynchronously. If the path to your own worker returns an 404, the worker will fail silently.

If your own application has multiple supinterfaceing javascript files, you can iminterface all of them iminterfaceScripts() method which takes file name(s) as argument separated simply simply by comma as follows −

iminterfaceScripts("helper.js", "one moreHelper.js");

Once the Web Worker is spawned, communication becometween web worker and it’s mother or father page is done uperform the postMessage() method. Depending on your own blineser/version, postMessage() can accept either a string or JSON object as it’s performle argument.

Message pbumed simply simply by Web Worker is accessed uperform onmessage take behaveionuallyt in the main page. Now enable us write our hugeLoop example uperform Web Worker. Below is the main page (hello.htm) which will spawn a web worker to execute the loop and to return the final value of variable j

<!DOCTYPE HTML>
<html>
   <mind>
      
      <title>Big for loop</title>
      
      <script>
         var worker = brand new Worker('hugeLoop.js');
         worker.onmessage = function (take behaveionuallyt) {
            alert("Compenableed " + take behaveionuallyt.data + "iterations" );
         };
         
         function sayHello(){
            alert("Hello sir...." );
         }
      </script>
      
   </mind>
   <body>
      
      <inplace kind="button" onclick="sayHello();" value="Say Hello"/>
      
   </body>
</html>

Folloearng is the content of hugeLoop.js file. This creates use of postMessage() API to pbum the communication back to main page −

for (var i = 0; i <= 1000000000; i += 1){
   var j = i;
}
postMessage(j);

This will produce folloearng result −

Now enable us keep hello.htm and hugeLoop.js file in the extake behaveion exbehave same directory and check to access hello.htm uperform lacheck version of either Safari or Firefox.

Stopping Web Workers

Web Workers don't quit simply simply by all of themselves but the page thead wear started all of them can quit all of them simply simply by calling terminate() method.

worker.terminate();

A terminated Web Worker will no longer respond to messages or perform any additional complaceations. You cannot restart a worker; instead, you can create a brand new worker uperform the extake behaveion exbehave same URL.

Handling Errors

The folloearng shows an example of an error handling function in a Web Worker JavaScript file thead wear logs errors to the console. With error handling code, above example would becomecome as folloearng −

<!DOCTYPE HTML>
<html>
   <mind>
      
      <title>Big for loop</title>
      
      <script>
         var worker = brand new Worker('hugeLoop.js');
         
         worker.onmessage = function (take behaveionuallyt) {
            alert("Compenableed " + take behaveionuallyt.data + "iterations" );
         };
         
         worker.onerror = function (take behaveionuallyt) {
            console.log(take behaveionuallyt.message, take behaveionuallyt);
         };
         
         function sayHello(){
            alert("Hello sir...." );
         }
      </script>
      
   </mind>
   <body>
   
      <inplace kind="button" onclick="sayHello();" value="Say Hello"/>
      
   </body>
</html>

Checcalifornia king for Blineser Supinterface

Folloearng is the syntax to detect a Web Worker feature supinterface available in a blineser

<!DOCTYPE HTML>
<html>
   <mind>
   
      <title>Big for loop</title>
      
      <script src="/js/modernizr-1.5.min.js"></script>
      
      <script>
         if (Modernizr.webworkers) {
            alert("Congratulation!! you have web workers supinterface." );
         }
         
         else{
            alert("Sorry!! you do not have web workers supinterface." );
         }
      </script>
   </mind>
   
   <body>
   
      <p>Checcalifornia king for Blineser Supinterface for web workers</p>
      
   </body>
</html>

This will produce folloearng result −

HTML5 – IndexedDB

The indexeddb is a brand new HTML5 concept to store the data inaspect user's blineser. indexeddb is more power than local storage and useful for applications thead wear requires to store big amount of the data. These applications can operate more efficiency and load faster.

Why to use indexeddb?

The W3C has announced thead wear the Web SQL database is a deprecated local storage specification so web createer should not use this particular technology any more. indexeddb is an alternative for web SQL data base and more effective than older technologies.

Features

  • it stores key-pair values
  • it is not a relational database
  • IndexedDB API is manyly asynchronous
  • it is not a structucrimson query language
  • it has supinterfaceed to access the data from extake behaveion exbehave same domain

IndexedDB

Before enter into an indexeddb, we need to add a couple of prefixes of implementation as shown becomelow

earndow.indexedDB = earndow.indexedDB || earndow.mozIndexedDB || earndow.webkitIndexedDB || earndow.msIndexedDB;
 
earndow.IDBTranstake behaveionion = earndow.IDBTranstake behaveionion || earndow.webkitIDBTranstake behaveionion || earndow.msIDBTranstake behaveionion;
earndow.IDBKeyRange = earndow.IDBKeyRange || earndow.webkitIDBKeyRange || earndow.msIDBKeyRange
 
if (!earndow.indexedDB) {
   earndow.alert("Your blineser doesn't supinterface a stable version of IndexedDB.")
}

Open an IndexedDB database

Before creating a database, we have to prepare a couple of data for the data base.enable's start with company employee details.

const employeeData = [
   { id: "01", name: "Gopal K Vprovidea", age: 35, email: "conttake [email protected]" },
   { id: "02", name: "Praunfortunate", age: 24, email: "[email protected]" }
];

Adding the data

Here adding a couple of data manually into the data as shown becomelow −

function add() {
   var request = db.transtake behaveionion(["employee"], "readwrite")
   .objectStore("employee")
   .add({ id: "01", name: "praunfortunate", age: 24, email: "[email protected]" });
   
   request.onsuccess = function(take behaveionuallyt) {
      alert("Praunfortunate has becomeen added to your own database.");
   };
   
   request.onerror = function(take behaveionuallyt) {
      alert("Unable to add datarnPraunfortunate is already exist in your own database! ");
   }
}

Retrieving Data

We can retrieve the data from the data base uperform with get()

function read() {
   var transtake behaveionion = db.transtake behaveionion(["employee"]);
   var objectStore = transtake behaveionion.objectStore("employee");
   var request = objectStore.get("00-03");
   
   request.onerror = function(take behaveionuallyt) {
      alert("Unable to retrieve daa from database!");
   };
   
   request.onsuccess = function(take behaveionuallyt) {
      if(request.result) {
         alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
      }
      
      else {
         alert("Kenny couldn't become found in your own database!");  
      }
   };
}

Uperform with get(), we can store the data in object instead of thead wear we can store the data in cursor and we can retrieve the data from cursor

function readAll() {
   var objectStore = db.transtake behaveionion("employee").objectStore("employee");
   
   objectStore.openCursor().onsuccess = function(take behaveionuallyt) {
      var cursor = take behaveionuallyt.target.result;
      
      if (cursor) {
         alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
         cursor.continue();
      }
      
      else {
         alert("No more entries!");
      }
   };
}

Removing the data

We can remove the data from IndexedDB with remove().Here is how the code looks like

function remove() {
   var request = db.transtake behaveionion(["employee"], "readwrite")
   .objectStore("employee")
   .deenablee("02");
   
   request.onsuccess = function(take behaveionuallyt) {
      alert("praunfortunate encheck has becomeen removed from your own database.");
   };
}

HTML Code

To show all the data we need to use onClick take behaveionuallyt as shown becomelow code −

<!DOCTYPE html>
<html>
   <mind>
   
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title>IndexedDb Demo | onlyWebPro.com</title>
   
   </mind>
   <body>
   
      <button onclick="read()">Read </button>
      <button onclick="readAll()"></button>
      <button onclick="add()"></button>
      <button onclick="remove()">Deenablee </button>
      
   </body>
</html>

Final code should become as

<!DOCTYPE html>
<html>
   <mind>
   
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <script kind="text/javascript">
         //prefixes of implementation thead wear we want to check
         earndow.indexedDB = earndow.indexedDB || earndow.mozIndexedDB || earndow.webkitIndexedDB || earndow.msIndexedDB;
         
         //prefixes of earndow.IDB objects
         earndow.IDBTranstake behaveionion = earndow.IDBTranstake behaveionion || earndow.webkitIDBTranstake behaveionion || earndow.msIDBTranstake behaveionion;
         earndow.IDBKeyRange = earndow.IDBKeyRange || earndow.webkitIDBKeyRange || earndow.msIDBKeyRange
         
         if (!earndow.indexedDB) {
            earndow.alert("Your blineser doesn't supinterface a stable version of IndexedDB.")
         }
         
         const employeeData = [
            { id: "00-01", name: "gopal", age: 35, email: "[email protected]" },
            { id: "00-02", name: "praunfortunate", age: 32, email: "[email protected]" }
         ];
         var db;
         var request = earndow.indexedDB.open("brand newDatabase", 1);
         
         request.onerror = function(take behaveionuallyt) {
            console.log("error: ");
         };
         
         request.onsuccess = function(take behaveionuallyt) {
            db = request.result;
            console.log("success: "+ db);
         };
         
         request.onupgradeneeded = function(take behaveionuallyt) {
            var db = take behaveionuallyt.target.result;
            var objectStore = db.createObjectStore("employee", {keyPath: "id"});
            
            for (var i in employeeData) {
               objectStore.add(employeeData[i]);
            }
         }
         
         function read() {
            var transtake behaveionion = db.transtake behaveionion(["employee"]);
            var objectStore = transtake behaveionion.objectStore("employee");
            var request = objectStore.get("00-03");
            
            request.onerror = function(take behaveionuallyt) {
               alert("Unable to retrieve daa from database!");
            };
            
            request.onsuccess = function(take behaveionuallyt) {
               // Do a couple ofthing with the request.result!
               if(request.result) {
                  alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
               }
               
               else {
                  alert("Kenny couldn't become found in your own database!");
               }
            };
         }
         
         function readAll() {
            var objectStore = db.transtake behaveionion("employee").objectStore("employee");
            
            objectStore.openCursor().onsuccess = function(take behaveionuallyt) {
               var cursor = take behaveionuallyt.target.result;
               
               if (cursor) {
                  alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
                  cursor.continue();
               }
               
               else {
                  alert("No more entries!");
               }
            };
         }
         
         function add() {
            var request = db.transtake behaveionion(["employee"], "readwrite")
            .objectStore("employee")
            .add({ id: "00-03", name: "Kenny", age: 19, email: "[email protected]" });
            
            request.onsuccess = function(take behaveionuallyt) {
               alert("Kenny has becomeen added to your own database.");
            };
            
            request.onerror = function(take behaveionuallyt) {
               alert("Unable to add datarnKenny is aready exist in your own database! ");
            }
         }
         
         function remove() {
            var request = db.transtake behaveionion(["employee"], "readwrite")
            .objectStore("employee")
            .deenablee("00-03");
            
            request.onsuccess = function(take behaveionuallyt) {
               alert("Kenny's encheck has becomeen removed from your own database.");
            };
         }
      </script>
      
   </mind>
   <body>
      
      <button onclick="read()">Read </button>
      <button onclick="readAll()">Read all </button>
      <button onclick="add()">Add data </button>
      <button onclick="remove()">Deenablee data </button>
      
   </body>
</html>

HTML5 – Web messaging

Web Messaging is the way for documents to separates blineperform context to share the data without Dom. It overrides the combination domain communication issue in different domains, protocols or interfaces.

For example you like to send the data from your own page to ad container which is placed at iframe or voice-versa, in this particular scenario,Blineser thlines a security other thanion. With web messaging we can pbum the data acombination as a message take behaveionuallyt.

Message Event

Message take behaveionuallyts fires Cross-document messaging, channel messaging, server-sent take behaveionuallyts and web sockets.it has describecomed simply simply by Message Event interface.

Attributes

Attributes Description
data Contains string data
origin Contains Domain name and interface
finalEventId Contains unique identifier for the current message take behaveionuallyt.
source Contains to A reference to the originating document’s earndow
interfaces Contains the data which is sent simply simply by any message interface

Sending a combination-document message

Before send combination document message, we need to create a brand new web blineperform context either simply simply by creating brand new iframe or brand new earndow. We can send the data uperform with postMessage() and it has 2 arguments. They are as

  • message − The message to send
  • targetOrigin − Origin name

Examples

Sending message from iframe to button

var iframe = document.querySelector('iframe');
var button = document.querySelector('button');

var clickHandler = function(){
   iframe.contentWindow.postMessage('The message to send.','https://www.tutorialsstage.com);
}
button.addEventListener('click',clickHandler,false);

Receiving a combination-document message in the receiving document

var messageEventHandler = function(take behaveionuallyt){
   // check thead wear the origin is one we want.
   if(take behaveionuallyt.origin == 'https://www.tutorialsstage.com'){
      alert(take behaveionuallyt.data);
	}
}
earndow.addEventListener('message', messageEventHandler,false);

Channel messaging

Two way communication becometween the blineperform contexts is caldirected channel messaging. It is useful for communication acombination multiple origins.

The MessageChannel and MessagePort Objects

While creating messageChannel,it internally creates 2 interfaces to sending the data and forbattdirecteded to one more blineperform context.

  • postMessage() − Post the message thline channel
  • start() − It sends the data
  • near() − it near the interfaces

In this particular scenario, we are sending the data from one iframe to one more iframe. Here we are invocalifornia king the data in function and pasperform the data to DOM.

var loadHandler = function(){
   var mc, interfaceMessageHandler;
   mc = brand new MessageChannel();
   earndow.mother or father.postMessage('documentAHasLoaded','http://foo.example',[mc.interface2]);
   
   interfaceMessageHandler = function(interfaceMsgEvent){
      alert( interfaceMsgEvent.data );
	}
   
   mc.interface1.addEventListener('message', interfaceMessageHandler, false);
   mc.interface1.start();
}
earndow.addEventListener('DOMContentLoaded', loadHandler, false);

Above code, it is tacalifornia king the data from interface 2, now it will pbum the data to 2nd iframe

var loadHandler = function(){
   var iframes, messageHandler;
   
   iframes = earndow.frames;
   messageHandler = function(messageEvent){
      if( messageEvent.interfaces.duration > 0 ){
         // transfer the interface to iframe[1]
         iframes[1].postMessage('interfaceopen','http://foo.example',messageEvent.interfaces);
      }
   }
   earndow.addEventListener('message',messageHandler,false);
}
earndow.addEventListener('DOMContentLoaded',loadHandler,false);

Now 2nd document handles the data simply simply by uperform the interfaceMsgHandler function.

var loadHandler(){
   // Define our message handler function
   var messageHandler = function(messageEvent){
   
      // Our form submission handler
      var formHandler = function(){
         var msg = 'add <[email protected]> to game circle.';
         messageEvent.interfaces[0].postMessage(msg);
      }
      document.forms[0].addEventListener('submit',formHandler,false);
   }
   earndow.addEventListener('message',messageHandler,false);
}
earndow.addEventListener('DOMContentLoaded',loadHandler,false);

HTML5 – CORS

Cross-origin resource sharing (CORS) is a mechanism to enables the restringented resources from one more domain in web blineser

For suppose, if you click on HTML5- video player in html5 demo sections. it will ask camera permission. if user enable the permission then only it will open the camera or else it doesn't open the camera for web applications

Macalifornia king a CORS request

here Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object, object.

function createCORSRequest(method, url) {
   var xhr = brand new XMLHttpRequest();
   
   if ("withCcrimsonentials" in xhr) {
      // Check if the XMLHttpRequest object has a "withCcrimsonentials" property or home or home.
      // "withCcrimsonentials" only exists on XMLHTTPRequest2 objects.
      xhr.open(method, url, true);
   }
   
   else if (kindof XDomainRequest != "undefined") {
      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of macalifornia king CORS requests.
      xhr = brand new XDomainRequest();
      xhr.open(method, url);
   }
   
   else {
      // Otherwise, CORS is not supinterfaceed simply simply by the blineser.
      xhr = null;
   }
   return xhr;
}

var xhr = createCORSRequest('GET', url);
if (!xhr) {
   thline brand new Error('CORS not supinterfaceed');
}

Event handles in CORS

Event Handler Description
onloadstart Starts the request
onprogress Loads the data and send the data
onabort Abort the request
onerror request has faidirected
onload request load successcomppermitey
ontimeout time out has happened becomefore request could compenablee
onloadend When the request is compenablee either successful or failure

Example of onload or onerror take behaveionuallyt

xhr.onload = function() {
   var responseText = xhr.responseText;
   
   // process the response.
   console.log(responseText);
};

xhr.onerror = function() {
   console.log('There was an error!');
};

Example of CORS with handler

Below example will show the example of createCorsRequest() and onload handler

// Create the XHR object.
function createCORSRequest(method, url) {
   var xhr = brand new XMLHttpRequest();
   
   if ("withCcrimsonentials" in xhr) {
      
      // XHR for Chrome/Firefox/Opera/Safari.
      xhr.open(method, url, true);
   }
   
   else if (kindof XDomainRequest != "undefined") {
      // XDomainRequest for IE.
      xhr = brand new XDomainRequest();
      xhr.open(method, url);
   }
   
   else {
      // CORS not supinterfaceed.
      xhr = null;
   }
   return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
   return text.fit('<title>(.*)?</title>')[1];
}

// Make the take behaveionual CORS request.
function createCorsRequest() {
   
   // All HTML5 Rocks propertie ups supinterface CORS.
   var url = 'http://www.tutorialsstage.com';
   
   var xhr = createCORSRequest('GET', url);
   
   if (!xhr) {
      alert('CORS not supinterfaceed');
      return;
   }
   
   // Response handlers.
   xhr.onload = function() {
      var text = xhr.responseText;
      var title = getTitle(text);
      alert('Response from CORS request to ' + url + ': ' + title);
   };
   
   xhr.onerror = function() {
      alert('Woops, generally generally there was an error macalifornia king the request.');
   };
   xhr.send();
}

HTML5 – Web RTC

Web RTC introduced simply simply by World Wide Web Consortium (W3C). Thead wear supinterfaces blineser-to-blineser applications for voice calling, video chead wear, and P2P file sharing.

If you like to check out? web RTC available for Chrome,opera,and firefox. A great place to start is the simple video chead wear application at here.Web RTC implements 3 API's as shown becomelow −

  • MediaStream − get access to the user's camera and miplantshone.
  • RTCPeerConnection − get access to audio or video calling facility.
  • RTCDataChannel − get access to peer-to-peer communication.

MediaStream

The MediaStream represents synchronized streams of media, For an example, Click on HTML5 Video player in HTML5 demo section or else click here.

The above example contains stream.getAudioTracks() and stream.VideoTracks(). If generally generally there is no audio tracks, it returns an empty array and it will check video stream,if webcam connected, stream.getVideoTracks() returns an array of one MediaStreamTrack representing the stream from the webcam. A simple example is chead wear applications, a chead wear applications gets stream from web camera, rear camera, miplantshone.

Sample code of MediaStream

function gotStream(stream) {
   earndow.AudioContext = earndow.AudioContext || earndow.webkitAudioContext;
   var audioContext = brand new AudioContext();
   
   // Create an AudioNode from the stream
   var mediaStreamSource = audioContext.createMediaStreamSource(stream);
   
   // Connect it to destination to hear your ownself
   // or any other node for procesperform!
   mediaStreamSource.connect(audioContext.destination);
}
navigator.getUserMedia({audio:true}, gotStream);

Screen capture

It's furthermore possible in chrome blineser with mediaStreamSource and it requicrimson HTTPS. This feature is not yet available in opera. Sample demo is available at here

Session Control, Ne2rk & Media Information

Web RTC requicrimson peer-to-peer communication becometween blinesers. This mechanism requicrimson signalling, ne2rk information, session manage and media information. Web createers can select different mechanism to communicate becometween the blinesers such as SIP or XMPP or any 2 way communications.A sample example of XHR is here.

Sample code of createSignalingChannel()

var signalingChannel = createSignalingChannel();
var pc;
var configuration = ...;

// operate start(true) to initiate a call
function start(isCaller) {
   pc = brand new RTCPeerConnection(configuration);
   
   // send any ice candidates to the other peer
   pc.onicecandidate = function (evt) {
      signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
   };
   
   // once remote stream arrives, show it in the remote video element
   pc.onaddstream = function (evt) {
      remoteView.src = URL.createObjectURL(evt.stream);
   };
   
   // get the local stream, show it in the local video element and send it
   navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
      selfView.src = URL.createObjectURL(stream);
      pc.addStream(stream);
      
      if (isCaller)
         pc.createOffer(gotDescription);
      
      else
         pc.createAnswer(pc.remoteDescription, gotDescription);
         
         function gotDescription(desc) {
            pc.setLocalDescription(desc);
            signalingChannel.send(JSON.stringify({ "sdp": desc }));
         }
      });
   }
   
   signalingChannel.onmessage = function (evt) {
      if (!pc)
         start(false);
         var signal = JSON.parse(evt.data);
      
      if (signal.sdp)
         pc.setRemoteDescription(brand new RTCSessionDescription(signal.sdp));
      
      else
         pc.addIceCandidate(brand new RTCIceCandidate(signal.candidate));
};
SHARE
Previous articlei
Next articleSix Sigma Introduction

NO COMMENTS

LEAVE A REPLY