HTML5 – Validation

HTML – Validation ”; Previous Next An HTML validator is a tool that parses each line of code in order to find syntax errors and to check whether the HTML and CSS codes comply with the latest standards set by the World Wide Consortium (W3C). The most frequently used validators are as follows − The W3C Markup Validator The W3C Markup Validator checks the markup validity of Web documents in HTML, XHTML, SMIL, MathML, etc. This validator is part of Unicorn, W3C”s unified validator service. To use this validator for HTML, you need to use More Options and select Document Type as HTML (experimental) as shown below. The Validator.nu (X)HTML Validator Here is the another currently known HTML5 validators: Henri”s Validator.nu (X)HTML5 Validator (Highly Experimental) − Print Page Previous Next Advertisements ”;

HTML5 – Geo-Location

HTML – Geolocation API ”; Previous Next HTML Geolocation API used by web applications to access geographical location of user. Most of the modern browsers and mobile devices support Geolocation API. JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. Syntax var geolocation = navigator.geolocation; The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device. Geolocation Methods The geolocation object provides the following methods: Method Description getCurrentPosition() This method retrieves the current geographic location of the user. watchPosition() This method retrieves periodic updates about the current geographic location of the device. clearWatch() This method cancels an ongoing watchPosition call. Following is a sample code to use any of the above methods: function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler); watchId = geolocation.watchPosition(showLocation, errorHandler, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }); navigator.geolocation.clearWatch(watchId); } Here showLocation and errorHandler are callback methods which would be used to get actual position as explained in next section and to handle errors if there is any. Location Properties Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information. The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The following table describes the properties of the Position object. For the optional properties if the system cannot provide a value, the value of the property 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 together with information about heading and speed. coords.latitude Number Specifies the latitude estimate in decimal degrees. The value range is [-90.00, +90.00]. coords.longitude Number Specifies the longitude estimate in decimal degrees. The value range is [-180.00, +180.00]. coords.altitude Number [Optional] Specifies the altitude estimate in meters above the WGS 84 ellipsoid. coords.accuracy Number [Optional] Specifies the accuracy of the latitude and longitude estimates in meters. coords.altitudeAccuracy Number [Optional] Specifies the accuracy of the altitude estimate in meters. coords.heading Number [Optional] Specifies the device”s current direction of movement in degrees counting clockwise relative to true north. coords.speed Number [Optional] Specifies the device”s current ground speed in meters per second. timestamp date Specifies the time when the location information was retrieved and the Position object created. Following is a sample code which makes use of position object. Here showLocation method is a callback method: function showLocation( position ) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; … } Handling Errors Geolocation is complicated, and it is very much required to catch any error and handle it gracefully. The geolocation methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties: Property Type Description code Number Contains a numeric code for the error. message String Contains a human-readable description of the error. The following table describes the possible error codes returned in the PositionError object. Code Constant Description 0 UNKNOWN_ERROR The method failed to retrieve the location of the device due to an unknown error. 1 PERMISSION_DENIED The method failed to retrieve the location of the device because the application does not have permission to use the Location Service. 2 POSITION_UNAVAILABLE The location of the device could not be determined. 3 TIMEOUT The method was unable to retrieve the location information within the specified maximum timeout interval. Following is a sample code which makes use of PositionError object. Here errorHandler method is a callback method: function errorHandler( err ) { if (err.code == 1) { // access is denied } … } Position Options Following is the actual syntax of getCurrentPosition() method: getCurrentPosition(callback, ErrorCallback, options) Here third argument is the PositionOptions object which specifies a set of options for retrieving the geographic location of the device. Following are the options which can be specified as third argument: Property Type Description enableHighAccuracy Boolean Specifies whether the widget wants to receive the most accurate location estimate possible. By default this is false. timeout Number The timeout property is the number of milliseconds your web application is willing to wait for a position. maximumAge Number Specifies the expiry time in milliseconds for cached location information. Following is a sample code which shows how to use above mentioned methods: function getLocation() { var geolocation = navigator.geolocation; geolocation.getCurrentPosition(showLocation, errorHandler, {maximumAge: 75000}); } Examples of HTML Geolocation API Here are some examples that shows how to access geolocation in HTML. Get Current Location The following code shows how to access current location of your device using JavaScript and

HTML5 – Audio Players

HTML – Audio Player ”; Previous Next HTML Local Audio Player with visualizer HTML features, include native audio and video support without the need for Flash.Below code works based HTML,CSS and Java Script.You can drag and drop your local Mp3 files into the container. Example Let”s look at the following example, where we are going to create a local audio visualizer HTML File <!DOCTYPE html> <html> <style> #instructions { width: 100%; text-align: center; top: 50%; margin-top: -100px; color: #DE3163; } #container { position: absolute; width: 100%; height: 100%; background: #D5F5E3; } #canvas-container { width: 600px; height: 600px; margin: auto; position: relative; top: 50%; margin-top: -263px; margin-right: -61px; } #canvas-copy { opacity: 0.05; -webkit-transform: scaleY(-1); margin-top: -6px; } </style> <body> <div id=”container”> <div id=”canvas-container”> <canvas width=600 height=300 id=”canvas”></canvas> <canvas width=600 height=300 id=”canvas-copy”></canvas> </div> <div id=”instructions”> <a href=”https://www.tutorialspoint.com/index.htm” align=”center”> Tutorials Point</a> <h2 style=”font-family:verdana”> Drag Your Local MP3 Files </h2> </div> <div id=”button”></div> </div> <script src=”js.html”></script> </body> </html> Now, we are going to create a javascript file with the name mentioned in the above HTML file js.html <script> (function() { var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; window.requestAnimationFrame = requestAnimationFrame; })(); window.onload = function() { var element = document.getElementById(”container”) dropAndLoad(element, init, “ArrayBuffer”) } function dropAndLoad(dropElement, callback, readFormat) { var readFormat = readFormat || “DataUrl” dropElement.addEventListener(”dragover”, function(e) { e.stopPropagation() e.preventDefault() e.dataTransfer.dropEffect = ”copy” }, false) dropElement.addEventListener(”drop”, function(e) { e.stopPropagation() e.preventDefault() loadFile(e.dataTransfer.files[0]) }, false) function loadFile(files) { var file = files var reader = new FileReader() reader.onload = function(e) { callback(e.target.result) } reader[”readAs” + readFormat](file) } } function init(arrayBuffer) { document.getElementById(”instructions”).innerHTML = ”Audio Loading” window.audioCtx = new AudioContext() window.analyser = audioCtx.createAnalyser() if (window.source) source.noteOff(0) audioCtx.decodeAudioData(arrayBuffer, function(buffer) { window.source = audioCtx.createBufferSource() source.buffer = buffer source.connect(analyser) analyser.connect(audioCtx.destination) source.start(0) var viz = new simpleViz() new visualizer(viz[”update”], analyser) document.getElementById(”instructions”).innerHTML = ”” }) } function visualizer(visualization, analyser) { var self = this this.visualization = visualization var last = Date.now() var loop = function() { var dt = Date.now() – last var byteFreq = new Uint8Array(analyser.frequencyBinCount) analyser.getByteFrequencyData(byteFreq) last = Date.now() self.visualization(byteFreq, dt) requestAnimationFrame(loop) } requestAnimationFrame(loop) } function simpleViz(canvas) { var self = this this.canvas = document.getElementById(”canvas”) this.ctx = this.canvas.getContext(“2d”) this.copyCtx = document.getElementById(”canvas-copy”).getContext(“2d”) this.ctx.fillStyle = ”#fff” this.barWidth = 10 this.barGap = 4 this.bars = Math.floor(this.canvas.width / (this.barWidth + this.barGap)) this.update = function(byteFreq) { self.ctx.clearRect(0, 0, self.canvas.width, self.canvas.height) var step = Math.floor(byteFreq.length / self.bars) for (var i = 0; i < self.bars; i++) { var barHeight = byteFreq[i * step] self.ctx.fillRect(i * (self.barWidth + self.barGap), self.canvas.height – barHeight, self.barWidth, barHeight) self.copyCtx.clearRect(0, 0, self.canvas.width, self.canvas.height) self.copyCtx.drawImage(self.canvas, 0, 0) } } } </script> Let”s combine both the file and observe the output we are going to get. <!DOCTYPE html> <html> <style> #instructions { width: 100%; text-align: center; top: 50%; margin-top: -100px; color: #DE3163; } #container { position: absolute; width: 100%; height: 100%; background: #D5F5E3; } #canvas-container { width: 600px; height: 600px; margin: auto; position: relative; top: 50%; margin-top: -263px; margin-right: -61px; } #canvas-copy { opacity: 0.05; -webkit-transform: scaleY(-1); margin-top: -6px; } </style> <body> <div id=”container”> <div id=”canvas-container”> <canvas width=600 height=300 id=”canvas”></canvas> <canvas width=600 height=300 id=”canvas-copy”></canvas> </div> <div id=”instructions”> <a href=”https://www.tutorialspoint.com/index.htm” align=”center”> Tutorials Point</a> <h2 style=”font-family:verdana”> Drag Your Local MP3 Files </h2> </div> <div id=”button”></div> </div> <script> (function() { var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; window.requestAnimationFrame = requestAnimationFrame; })(); window.onload = function() { var element = document.getElementById(”container”) dropAndLoad(element, init, “ArrayBuffer”) } function dropAndLoad(dropElement, callback, readFormat) { var readFormat = readFormat || “DataUrl” dropElement.addEventListener(”dragover”, function(e) { e.stopPropagation() e.preventDefault() e.dataTransfer.dropEffect = ”copy” }, false) dropElement.addEventListener(”drop”, function(e) { e.stopPropagation() e.preventDefault() loadFile(e.dataTransfer.files[0]) }, false) function loadFile(files) { var file = files var reader = new FileReader() reader.onload = function(e) { callback(e.target.result) } reader[”readAs” + readFormat](file) } } function init(arrayBuffer) { document.getElementById(”instructions”).innerHTML = ”Audio Loading” window.audioCtx = new AudioContext() window.analyser = audioCtx.createAnalyser() if (window.source) source.noteOff(0) audioCtx.decodeAudioData(arrayBuffer, function(buffer) { window.source = audioCtx.createBufferSource() source.buffer = buffer source.connect(analyser) analyser.connect(audioCtx.destination) source.start(0) var viz = new simpleViz() new visualizer(viz[”update”], analyser) document.getElementById(”instructions”).innerHTML = ”” }) } function visualizer(visualization, analyser) { var self = this this.visualization = visualization var last = Date.now() var loop = function() { var dt = Date.now() – last var byteFreq = new Uint8Array(analyser.frequencyBinCount) analyser.getByteFrequencyData(byteFreq) last = Date.now() self.visualization(byteFreq, dt) requestAnimationFrame(loop) } requestAnimationFrame(loop) } function simpleViz(canvas) { var self = this this.canvas = document.getElementById(”canvas”) this.ctx = this.canvas.getContext(“2d”) this.copyCtx = document.getElementById(”canvas-copy”).getContext(“2d”) this.ctx.fillStyle = ”#fff” this.barWidth = 10 this.barGap = 4 this.bars = Math.floor(this.canvas.width / (this.barWidth + this.barGap)) this.update = function(byteFreq) { self.ctx.clearRect(0, 0, self.canvas.width, self.canvas.height) var step = Math.floor(byteFreq.length / self.bars) for (var i = 0; i < self.bars; i++) { var barHeight = byteFreq[i * step] self.ctx.fillRect(i * (self.barWidth + self.barGap), self.canvas.height – barHeight, self.barWidth, barHeight) self.copyCtx.clearRect(0, 0, self.canvas.width, self.canvas.height) self.copyCtx.drawImage(self.canvas, 0, 0) } } } </script> </body> </html> When we run the above code, it will generate an output consisting of the text applied with CSS indicating to drag the local MP3 file to play music. Local Audio Player with play list Consider the following example, where we are allowing the user to upload the multiple local MP3 that acts a playlist. <!DOCTYPE html> <html> <body style=”background-color:#ABEBC6;”> <audio controls id=”y” autoplay></audio> <br> <br> <br> <input type=”file” id=”x” multiple> <script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script> <script> var x = document.getElementById(“x”), y = document.getElementById(“y”); function next(n) { var a = URL.createObjectURL(z[n]); y.setAttribute(”src”, a); y.play(); } var _next = 0, z, len; x.addEventListener(”Change”, function() { z = x.z; len = z.length; if (len) { next(_next); } }); y.addEventListener(“Completed”, function() { _next += 1; next(_next); console.log(len, _next); if ((len – 1) == _next) { _next = -1; } }); </script> </body> </html> On running the above code, the output window will pop up, allowing the user to upload multiple mp3 files and plays automatically on the webpage. Print Page Previous Next Advertisements ”;

HTML5 – Web Messaging

HTML – Web Messaging ”; Previous Next Web Messaging is the way for documents to separates browsing context to share the data without Dom. It overrides the cross domain communication problem in different domains, protocols or ports. For example, if we want to send the data from our page to ad container which is placed at iframe or voice-versa, in this scenario, Browser throws a security exception. With web messaging we can pass the data across as a message event. Message Event Message events fires Cross-document messaging, channel messaging, server-sent events and web sockets. It is described by Message Event interface. Properties of Message Event The following table contains a list of Message Event properties − S.No. Property & Description 1 data Contains string data 2 origin Contains Domain name and port 3 lastEventId Contains unique identifier for the current message event. 4 source Contains to A reference to the originating document’s window 5 ports Contains the data which is sent by any message port Sending a cross-document message Before send cross document message, we need to create a new web browsing context either by creating new iframe or new window. We can send the data using with postMessage() and it has two 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.tutorialspoint.com); } button.addEventListener(”click”,clickHandler,false); Receiving a cross-document message in the receiving document var messageEventHandler = function(event){ // check that the origin is one we want. if(event.origin == ”https://www.tutorialspoint.com”){ alert(event.data); } } window.addEventListener(”message”, messageEventHandler,false); Channel messaging Two-way communication between the browsing contexts is called channel messaging. It is useful for communication across multiple origins. The MessageChannel and MessagePort Objects While creating messageChannel, it internally creates two ports to sending the data and forwarded to another browsing context. postMessage() − Post the message throw channel start() − It sends the data close() − it close the ports In this scenario, we are sending the data from one iframe to another iframe. Here we are invoking the data in function and passing the data to DOM. var loadHandler = function(){ var mc, portMessageHandler; mc = new MessageChannel(); window.parent.postMessage(”documentAHasLoaded”,”http://foo.example”,[mc.port2]); portMessageHandler = function(portMsgEvent){ alert( portMsgEvent.data ); } mc.port1.addEventListener(”message”, portMessageHandler, false); mc.port1.start(); } window.addEventListener(”DOMContentLoaded”, loadHandler, false); Above code, it is taking the data from port 2, now it will pass the data to second iframe var loadHandler = function(){ var iframes, messageHandler; iframes = window.frames; messageHandler = function(messageEvent){ if( messageEvent.ports.length > 0 ){ // transfer the port to iframe[1] iframes[1].postMessage(”portopen”,”http://foo.example”,messageEvent.ports); } } window.addEventListener(”message”,messageHandler,false); } window.addEventListener(”DOMContentLoaded”,loadHandler,false); Now second document handles the data by using the portMsgHandler 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.ports[0].postMessage(msg); } document.forms[0].addEventListener(”submit”,formHandler,false); } window.addEventListener(”message”,messageHandler,false); } window.addEventListener(”DOMContentLoaded”,loadHandler,false); Print Page Previous Next Advertisements ”;

HTML5 – IndexedDB

HTML – IndexedDB ”; Previous Next The indexedDB is a new HTML5 concept to store the data inside user”s browser. It is more powerful than local storage and useful for applications that requires to store large amount of the data. These applications can run more efficiency and load faster. Why to use indexedDB? The W3C has announced that the Web SQL database is a deprecated local storage specification so web developer should not use this technology any more. The 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 mostly asynchronous It is not a structured query language It allows to access the data from same domain IndexedDB Before enter into an indexedDB, we need to add some prefixes of implementation as shown below − window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange if (!window.indexedDB) { window.alert(“Your browser doesn”t support a stable version of IndexedDB.”) } Open an IndexedDB database Before creating a database, we have to prepare some data for the data base.let”s start with company employee details. const employeeData = [ { id: “01”, name: “Gopal K Varma”, age: 35, email: “[email protected]” }, { id: “02”, name: “Prasad”, age: 24, email: “[email protected]” } ]; Adding the data Here adding some data manually into the data as shown below − function add() { var request = db.transaction([“employee”], “readwrite”) .objectStore(“employee”) .add({ id: “01”, name: “prasad”, age: 24, email: “[email protected]” }); request.onsuccess = function(event) { alert(“Prasad has been added to your database.”); }; request.onerror = function(event) { alert(“Unable to add datarnPrasad is already exist in your database! “); } } Retrieving Data We can retrieve the data from the data base using with get() function read() { var transaction = db.transaction([“employee”]); var objectStore = transaction.objectStore(“employee”); var request = objectStore.get(“00-03”); request.onerror = function(event) { alert(“Unable to retrieve daa from database!”); }; request.onsuccess = function(event) { if(request.result) { alert(“Name: ” + request.result.name + “, Age: ” + request.result.age + “, Email: ” + request.result.email); } else { alert(“Kenny couldn”t be found in your database!”); } }; } Using with get(), we can store the data in object instead of that we can store the data in cursor and we can retrieve the data from cursor function readAll() { var objectStore = db.transaction(“employee”).objectStore(“employee”); objectStore.openCursor().onsuccess = function(event) { var cursor = event.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 using the remove() method. Here is how the code looks like − function remove() { var request = db.transaction([“employee”], “readwrite”) .objectStore(“employee”) .delete(“02”); request.onsuccess = function(event) { alert(“prasad entry has been removed from your database.”); }; } HTML Code To show all the data we need to use onClick event as shown below code − <!DOCTYPE html> <html> <head> <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ /> <title>IndexedDb Demo | onlyWebPro.com</title> </head> <body> <button onclick=”read()”>Read </button> <button onclick=”readAll()”></button> <button onclick=”add()”></button> <button onclick=”remove()”>Delete </button> </body> </html> The final code should be as − <!DOCTYPE html> <html> <head> <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ /> <script type=”text/javascript”> //prefixes of implementation that we want to test window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; //prefixes of window.IDB objects window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange if (!window.indexedDB) { window.alert(“Your browser doesn”t support a stable version of IndexedDB.”) } const employeeData = [ { id: “00-01”, name: “gopal”, age: 35, email: “[email protected]” }, { id: “00-02”, name: “prasad”, age: 32, email: “[email protected]” } ]; var db; var request = window.indexedDB.open(“newDatabase”, 1); request.onerror = function(event) { console.log(“error: “); }; request.onsuccess = function(event) { db = request.result; console.log(“success: “+ db); }; request.onupgradeneeded = function(event) { var db = event.target.result; var objectStore = db.createObjectStore(“employee”, {keyPath: “id”}); for (var i in employeeData) { objectStore.add(employeeData[i]); } } function read() { var transaction = db.transaction([“employee”]); var objectStore = transaction.objectStore(“employee”); var request = objectStore.get(“00-03”); request.onerror = function(event) { alert(“Unable to retrieve daa from database!”); }; request.onsuccess = function(event) { // Do something 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 be found in your database!”); } }; } function readAll() { var objectStore = db.transaction(“employee”).objectStore(“employee”); objectStore.openCursor().onsuccess = function(event) { var cursor = event.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.transaction([“employee”], “readwrite”) .objectStore(“employee”) .add({ id: “00-03”, name: “Kenny”, age: 19, email: “[email protected]” }); request.onsuccess = function(event) { alert(“Kenny has been added to your database.”); }; request.onerror = function(event) { alert(“Unable to add datarnKenny is aready exist in your database! “); } } function remove() { var request = db.transaction([“employee”], “readwrite”) .objectStore(“employee”) .delete(“00-03”); request.onsuccess = function(event) { alert(“Kenny”s entry has been removed from your database.”); }; } </script> </head> <body> <button onclick=”read()”>Read </button> <button onclick=”readAll()”>Read all </button> <button onclick=”add()”>Add data </button> <button onclick=”remove()”>Delete data </button> </body> </html> Print Page Previous Next Advertisements ”;

HTML5 – Microdata

HTML – Microdata ”; Previous Next Microdata is a standardized way to provide additional semantics in the web pages. It lets us define our own customized elements and start embedding custom properties in the web pages. The microdata consists of a group of name-value pairs. The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements. Using Microdata in HTML document Earlier, we mentioned that the microdata has group of name-value pairs (property) and this group is known as items. To create an item, the itemscope attribute is used. To add a property to an item, the itemprop attribute is used on one of the item”s descendants. Example In this example, there are two items, each of which has the property “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> Properties generally have values that are strings but it can have following data types − Global Attributes Microdata introduces five global attributes which would be available for any element to use and give context for machines about your data. S.No. Attribute & Description 1 itemscope This is used to create an item. The itemscope attribute is a Boolean attribute that tells that there is Microdata on this page, and this is where it starts. 2 itemtype This attribute is a valid URL which defines the item and provides the context for the properties. 3 itemid This attribute is global identifier for the item. 4 itemprop This attribute defines a property of the item. 5 itemref This attribute gives a list of additional elements to crawl to find the name-value pairs of the item. Properties Datatypes Properties generally have values that are strings as mentioned in above example but they can also have values that are URLs. Following example has one property, “image”, whose value is a URL − <div itemscope> <img itemprop=”image” src=”tp-logo.gif” alt=”TutorialsPoint”> </div> Properties can also have values that are dates, times, or dates and times. This is achieved using the time element and its datetime attribute. <html> <body> <div itemscope> My birthday is − <time itemprop=”birthday” datetime=”1971-05-08″> Aug 5th 1971 </time> </div> </body> </html> Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property. Microdata API support If a browser supports the HTML5 microdata API, there will be a getItems() function on the global document object. If browser doesn”t support microdata, the getItems() function will be undefined. function supports_microdata_api() { return !!document.getItems; } Modernizr does not yet support checking for the microdata API, so we will need to use the function like the one listed above. The HTML5 microdata standard includes both HTML markup (primarily for search engines) and a set of DOM functions (primarily for browsers). We can include microdata markup in our web pages and the search engines that are not capable to understand the microdata attributes will just ignore them. But if we need to access or manipulate microdata through the DOM, we need to check whether the browser supports the microdata DOM API. Defining Microdata Vocabulary To define microdata vocabulary, you need a namespace URL which points to a working web page. For example, http://data-vocabulary.org/Person can be used as the namespace for a personal microdata vocabulary with the following named properties − name − Person name as a simple string Photo − A URL to a picture of the person. URL − A website belonging to the person. Using about properties a person microdata could be as follows − <html> <body> <div itemscope> <section itemscope itemtype=”http://data-vocabulary.org/Person”> <h1 itemprop=”name”>Gopal K Varma</h1> <p> <img itemprop=”photo” src=”http://www.tutorialspoint.com/green/images/logo.png”> </p> <a itemprop=”url” href=”#”>Site</a> </section> </div> </body> </html> Google supports microdata as part of their Rich Snippets program. When Google”s web crawler parses your page and finds microdata properties that conform to the vocabulary, it parses out those properties and stores them alongside the rest of the page data. For further development on Microdata you can always refer to HTML5 Microdata. Print Page Previous Next Advertisements ”;

HTML5 – Server-Sent Events

HTML – Server Sent Events ”; Previous Next Server Sent Events are a way of sending data from a server to a web page, without requiring the page to refresh or make requests. These events are useful for creating real-time applications, such as chat, news feeds, or notifications. Using SSE, we can push DOM events continuously from our web server to the visitor”s browser. The event streaming approach opens a persistent connection to the server, sending data to the client when new information is available, eliminating the need for continuous polling. Server-sent events standardize how we stream data from the server to the client. How to use SSE in Web Application? To use Server-Sent Events in a web application, we need to add an <eventsource> element to the document. The src attribute of <eventsource> element should point to an URL which provides a persistent HTTP connection that sends a data stream containing the events. Furthermore, the URL points to a PHP, PERL or any Python script which would take care of sending event data consistently. Instance Following is a sample HTML code of web application which would expect server time. <!DOCTYPE html> <html> <head> <script type=”text/javascript”> /* Define event handling logic here */ </script> </head> <body> <div id=”sse”> <eventsource src=”/cgi-bin/ticker.cgi” /> </div> <div id=”ticker”> <TIME> </div> </body> </html> Server Side Script for SSE A server side script should send Content-type header specifying the type text/event-stream as follows. print “Content-Type: text/event-streamnn”; After setting Content-Type, server side script would send an Event: tag followed by event name. Following code snippet would send Server-Time as event name terminated by a new line character. print “Event: server-timen”; Final step is to send event data using Data: tag which would be followed by integer of string value terminated by a new line character as follows − $time = localtime(); print “Data: $timen”; Finally, following is complete ticker.cgi written in Perl − #!/usr/bin/perl print “Content-Type: text/event-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 events. Following is the final example. <!DOCTYPE html> <html> <head> <script type=”text/javascript”>document.getElementsByTagName(“eventsource”)[0].addEventListener(“server-time”, eventHandler, false); function eventHandler(event) { // Alert time sent by the server document.querySelector(”#ticker”).innerHTML = event.data; } </script> </head> <body> <div id=”sse”> <eventsource src=”/cgi-bin/ticker.cgi” /> </div> <div id=”ticker” name=”ticker”> [TIME] </div> </body> </html> Before testing Server-Sent events, I would suggest that you make sure your web browser supports this concept. Print Page Previous Next Advertisements ”;

HTML5 – Web Worker

HTML5 – Web Workers ”; Previous Next JavaScript was designed to run in a single-threaded environment, meaning multiple scripts cannot run at the same time. Consider a situation where you need to handle UI events, query and process large amounts of API data, and manipulate the DOM. You can get source code at here Print Page Previous Next Advertisements ”;