Detection Techniques

There are four basic techniques for detecting whether a browser supports a particular feature. From simplest to most complex: #1:Check if a certain property exists on a global object (such as window or navigator).For an example of testing for geolocation support. #2:Create an element, then check if a certain property exists on that element.For an example of testing for canvas support. #3:Create an element, check if a certain method exists on that element, then call themethod and check the value it returns.For an example of testing which video formats are supported. #4:Create an element, set a property to a certain value, then check if the property hasretained its value.For an example of testing which <input> types are supported.

Modernizr is an open-source JavaScript library that helps you build the next generation
of HTML5 and CSS3-powered websites.

Why use Modernizr?
Taking advantage of the new capabilities of HTML5 and CSS3 can mean sacrificing control over the experience in older browsers.When it runs, it creates a global object called Modernizr that contains a set of Boolean properties for each feature it can detect. For example if (Modernizr.feature) { // return true if your browser support feature like canvas, video } else { // return false if your browser dosent support feature }

Canvas
HTML5 defines the<canvas> element as “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.”.and defines a set of functions (“the canvas API”) for drawing shapes, defining paths, creating gradients, and applying transformations You can check for canvas support using this function: function supports_canvas() { return !!document.createElement(„canvas‟).getContext;

} or we can use Modernizr for check if your browser support canvas. if (Modernizr.canvas) { // let‟s draw some shapes! } else { // no native canvas support available }

Video
HTML5 defines a new element called for embedding video in your web pages.Checking for video support uses detection technique #2.if your browser dosent support video there is a solution called Video for Everybody! This solution uses no JavaScript whatsoever, and it works in virtually every browser, including mobile browsers. You can check for video support using this function: function supports_video() { return !!document.createElement(„video‟).canPlayType; } or we can use Modernizr for check if your browser support Video.

Video Formats
Video formats are like languages.The “language” of a video is called a “codec”.Checking for video format support uses detection technique #3. function supports_h264_baseline_video() { if (!supports_video()) { return false; } var v = document.createElement(“video”); return v.canPlayType(„video/mp4,ogg or webm; codecs=”avc1.42E01E, mp4a.40.2″,”theora, vorbis”or”vp8, vorbis”„); } The canPlayType() function doesn‟t return true or false. In recognition of how complex video formats are, the function returns a string:
“probably”

If the browser is fairly confident it can play this format.
“maybe”

Checking for geolocation support uses detection technique #1 Here‟s how to checkfor geolocation support: function supports_geolocation() { return !!navigator.more or less. With web workers. } Instead of writing this function yourself.If the browser thinks it might be able to play this format. Checking for HTML5 Storage support uses detection technique #1. you can spawn multiple “threads” that all run at the same time. you can use Modernizr. } Instead of writing this function yourself.This function checks for web worker support: function supports_web_workers() { return !!window.Checking for web workers uses detection technique #1. } Instead of writing this function yourself. Web Workers Web workers provide a standard way for browsers to run JavaScript in the background.geolocation.Worker. “” (an empty string) If the browser is certain it can‟t play this format. you can use Modernizr. you can use Modernizr . or we can use Modernizr for check if your browser support Video Formats Local Storage HTML5 Storageprovides a way for websites to store information on your computer and retrieve it later.You can check for local storage support using this function: function supports_local_storage() { return („localStorage‟ in window) && window['localStorage'] !== null. Geolocation Geolocation is the art of figuring out where you are in the world and (optionally) sharing that information with people you trust.

Here‟s how to check for placeholder support: function supports_input_placeholder() { var i = document.setAttribute(“type”. } var i = document. } Instead of writing this function yourself. . Checking for placeholder support uses detection technique #2.createElement(„input‟). return „placeholder‟ in i. the placeholder text disappears . you can use Modernizr. Placeholder Text Placeholder text is displayed inside the input field as long as the field is empty and not focused. Form Autofocus use to focus the first input field of a web form automatically. function supports_Input_Type() { if (!supports_Input_Type()) { return false. i. “color”). you can use Modernizr. As soon as you click on (or tab to) the input field.type !== “color”. } Instead of writing this function yourself. Checking for autofocus support uses detection technique #2.Input Types Checking for HTML5 input types uses detection technique #4.createElement(„input‟).createElement(“input”). return i. You can detect autofocus support with this function: function supports_input_autofocus() { var i = document.

HTML5 New Input Types HTML5 has several new input types for forms. These new features allow better input control and validation. you can already start using them.return „autofocus‟ in i. } Instead of writing this function yourself. However. This chapter covers the new input types:              color date datetime datetime-local email month number range search tel time url week Note: Not all major browsers support all the new input types. Example Select a color from a color picker: Select your favorite color: <input type="color" name="favcolor"> . Input Type: color The color type is used for input fields that should contain a color. If they are not supported. they will behave as regular text fields. Q5. you can use Modernizr.

Example Define a date and time control (with time zone): Birthday (date and time): <input type="datetime" name="bdaytime"> Try it yourself » .Try it yourself » Input Type: date The date type allows the user to select a date. Example Define a date control: Birthday: <input type="date" name="bday"> Try it yourself » Input Type: datetime The datetime type allows the user to select a date and time (with time zone).

Example Define a date and time control (no time zone): Birthday (date and time): <input type="datetime-local" name="bdaytime"> Try it yourself » Input Type: email The email type is used for input fields that should contain an e-mail address.com options).Input Type: datetime-local The datetime-local type allows the user to select a date and time (no time zone). and changes the on-screen keyboard to match it (adds @ and . Input Type: month The month type allows the user to select a month and year. . Example Define a field for an e-mail address (will be automatically validated when submitted): E-mail: <input type="email" name="email"> Try it yourself » Tip: Safari on iPhone recognizes the email type.

You can also set restrictions on what numbers are accepted: Example Define a numeric field (with restrictions): Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5"> Try it yourself » Use the following attributes to specify restrictions:     max .specifies the legal number intervals value .Example Define a month and year control (no time zone): Birthday (month and year): <input type="month" name="bdaymonth"> Try it yourself » Input Type: number The number type is used for input fields that should contain a numeric value.specifies the maximum value allowed min .Specifies the default value Try an example with all the restriction attributes: Try it yourself .specifies the minimum value allowed step .

specifies the minimum value allowed step . Example Define a search field (like a site search.Input Type: range The range type is used for input fields that should contain a value from a range of numbers. Example Define a control for entering a number whose exact value is not important (like a slider control): <input type="range" name="points" min="1" max="10"> Try it yourself » Use the following attributes to specify restrictions:     max .specifies the maximum value allowed min .specifies the legal number intervals value .Specifies the default value Input Type: search The search type is used for search fields (a search field behaves like a regular text field). or Google search): Search Google: <input type="search" name="googlesearch"> Try it yourself » . You can also set restrictions on what numbers are accepted.

Example Define a control for entering a time (no time zone): Select a time: <input type="time" name="usr_time"> Try it yourself » Input Type: url The url type is used for input fields that should contain a URL address. . The value of the url field is automatically validated when the form is submitted.Input Type: tel Example Define a field for entering a telephone number: Telephone: <input type="tel" name="usrtel"> Try it yourself » Input Type: time The time type allows the user to select a time.

com option). and changes the on-screen keyboard to match it (adds . Input Type: week The week type allows the user to select a week and year.Example Define a field for entering a URL: Add your homepage: <input type="url" name="homepage"> Try it yourself » Tip: Safari on iPhone recognizes the url input type. Example Define a week and year control (no time zone): Select a week: <input type="week" name="week_year"> Try it yourself » HTML5 <input> Tag Tag <input> Description Defines an input control .

ogg" controls> Your browser does not support the <code>video</code> element. </video> This example plays a sample video.New Media Elements HTML5 offers new elements for media content: Tag <audio> <video> <source> <embed> <track> Description Defines sound content Defines a video or movie Defines multiple media resources for <video> and <audio> Defines a container for an external application or interactive content (a plug-in) Defines text tracks for <video> and <audio> Embedding media in your HTML document is trivial: 1 2 3 site. <video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg"> <p>Your browser does not support the audio element. 1 <audio src="audio.ogg" controls autoplay loop> <p>Your browser does not support the audio element </p> 2 </audio> 3 This code example uses attributes of the <audio> element:   controls : Displays the standard HTML5 controls for the audio on the web page.</p> 2 </audio> 3 The src attribute can be a URL of the audio file or the path to the file on the local system. . with playback controls. from the Theora web Here is an example for embedding audio into your HTML document 1 <audio src="/test/audio. autoplay : Makes the audio play automatically.

mp3" preload="auto" controls></audio> 1 The preload attribute is used in the audio element for buffering large files. the browser uses the MPEG-4 file. For instance: 1 2 3 4 5 <video controls> <source src="foo.mp4" type="video/mp4"> Your browser does not support the <code>video</code> element. </video> localStorage and sessionStorage There are two new objects for storing data on the client:   localStorage . <audio src="audio. loop : Make the audio repeat (loop) automatically. codecs=dirac.stores data for one session Before using web storage. You may also specify which codecs the media file requires. If the browser doesn't support Ogg. check browser support for localStorage and sessionStorage: . </video> This plays the Ogg file in browsers supporting the Ogg format. It can take one of 3 values:    "none" does not buffer the file "auto" buffers the media file "metadata" buffers only the metadata for the file Multiple source files can be specified using the <source> element in order to provide video or audio encoded in different formats for different browsers. this allows the browser to make even more intelligent decisions: 1 2 3 4 <video controls> <source src="foo.stores data with no expiration date sessionStorage .ogg" type="video/ogg"> <source src="foo. speex"> Your browser does not support the <code>video</code> element.ogg" type="video/ogg. See also the list of media formats supported by the audio and video elements in different browsers.

The data will not be deleted when the browser is closed.clickcount=Number(localStorage.. } The localStorage Object The localStorage object stores the data with no expiration date. The following example counts the number of times a user has clicked a button.lastname.. week...lastname="Smith".if(typeof(Storage)!=="undefined") { // Yes! localStorage and sessionStorage support! // Some code.clickcount)+1. Try it yourself » Example explained:   Create a localStorage key/value pair with key="lastname" and value="Smith" Retrieve the value of the "lastname" key and insert it into the element with id="result" Tip: Key/value pairs are always stored as strings. Remember to convert them to another format when needed. Example localStorage. In this code the value string is converted to a number to be able to increase the counter: Example if (localStorage. or year. and will be available the next day.clickcount) { localStorage. } else { // Sorry! No web storage support. } .innerHTML="Last name: " + localStorage.getElementById("result"). document..

clickcount)+1.clickcount) { sessionStorage. except that it stores the data for only one session.clickcount=Number(sessionStorage. The data is deleted when the user closes the browser window.". The following example counts the number of times a user has clicked a button. .innerHTML="You have clicked the button " + sessionStorage. via scripting (usually JavaScript).clickcount=1. in the current session: Example if (sessionStorage. The <canvas> element is only a container for graphics. } document.clickcount + " time(s). Try it yourself » What is Canvas? The HTML5 <canvas> element is used to draw graphics. } else { sessionStorage.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount=1. on the fly.clickcount + " time(s) in this session. Try it yourself » The sessionStorage Object The sessionStorage object is equal to the localStorage object.else { localStorage. You must use a script to actually draw the graphics. } document.".getElementById("result").

the <canvas> element has no border and no content. do not support the <canvas> element. Opera. circles. and it is specified with the <canvas> element. </canvas> . Note: By default. <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000. and Safari support the <canvas> element. The markup looks like this: <canvas id="myCanvas" width="200" height="100"></canvas> Note: Always specify an id attribute (to be referred to in a script). boxes."> Your browser does not support the HTML5 canvas tag. Firefox. and adding images. Create a Canvas A canvas is a rectangular area on an HTML page. characters. Chrome. Browser Support Internet Explorer 9+. Note: Internet Explorer 8 and earlier versions.Canvas has several methods for drawing paths. Tip: You can have multiple <canvas> elements on one HTML page. and a width and height attribute to define the size of the canvas.

"> Your browser does not support the HTML5 canvas tag.50. ctx.PI). ctx.0. </script> </body> </html> .getElementById("myCanvas").</canvas> <script> var c=document.</body> </html> Example for drawing circle <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3.beginPath().arc(95.getContext("2d").2*Math. ctx.40.stroke(). var ctx=c.

(It wasn’t invented until 1994. the web server sends “headers” before it sends the actual page markup. and so on). image/png for PNG images. CSS stylesheets have their own MIME type. The first generation of web servers (and I’m talking web servers from 1993) didn’t send the Content-Type header because it didn’t exist yet. Of course. Images have their own MIME types (image/jpeg forJPEG images. some popular web browsers will ignore the Content-Type header under certain circumstances. JavaScript files have their own MIME type. everything you’ve ever looked . and therefore how it should be rendered. This header is the only thing that determines what a particular resource truly is. (This is called “content sniffing. reality is more complicated than that. But to understand the history of HTML5 and the motivations behind it.”) But as a general rule of thumb. The web runs on MIME types. because they tell your browser how to interpret the page markup that follows. Specifically. But the headers are important. and not any version of XHTML.MIME TYPES This book is about HTML5. although there are web development tools that will make them visible if you’re interested. These headers are normally invisible.) For compatibility reasons that date all the way back to 1993. Every time your web browser requests a page. MIME types. you need to understand a few technical details first. Everything has its own MIME type. The most important header is called Content-Type. not previous versions of HTML. and it looks like this: Content-Type: text/html “text/html” is called the “content type” or “MIME type” of the page.

scripts. We’ll come back to it. Locate the User's Position The HTML5 Geolocation API is used to get the geographical position of a user.getCurrentPosition(showPosition). Chrome. HTML5 . } .Using Geolocation Use the getCurrentPosition() method to get the user's position.at on the web — HTMLpages. Browser Support Internet Explorer 9+. anything with a URL — has been served to you with a specific MIME type in theContent-Type header. PDFs. the position is not available unless the user approves it. Since this can compromise user privacy. Safari and Opera support Geolocation.geolocation) { navigator. videos. like iPhone. Tuck that under your hat. The example below is a simple Geolocation example returning the latitude and longitude of the user's position: Example <script> var x=document. Firefox.getElementById("demo"). Note: Geolocation is much more accurate for devices with GPS. images.geolocation. function getLocation() { if (navigator.

so that browser developers can standardize and save time and money. HTML4 lacks rules for parsing. If not.coords. the ability to write malformed code and have it corrected into a valid document.} } function showPosition(position) { x. so developers just have to test malformed documents in various browsers (especially Internet Explorer) to handle any errors. Also.". display a message to the user If the getCurrentPosition() method is successful. } </script> Example explained:     Check if Geolocation is supported If supported.latitude + "<br>Longitude: " + position. it returns a coordinates object to the function specified in the parameter ( showPosition ) The showPosition() function gets the displays the Latitude and Longitude The example above is a very basic Geolocation script. which makes it more difficult to handle errors.coords.innerHTML="Latitude: " + position. this is.else{x. Errorhandling HTML4 supports what is called ‘tag soup’. with no error handling. HTML5 is attempting to solve this. It is also more flexible to handle inaccurate syntax.longitude. run the getCurrentPosition() method.innerHTML="Geolocation is not supported by this browser. But the problem is that rules for doing this aren’t written anywhere. What is W3C?         W3C W3C W3C W3C W3C W3C W3C W3C Stands for the World Wide Web Consortium was created in October 1994 was created by Tim Berners-Lee was created by the Inventor of the Web is organized as a Member Organization is working to Standardize the Web creates and maintains WWW Standards Standards are called W3C Recommendations . and it specifies the rules related to the parsing and lexing.

education. Tim Berners-Lee . Defense Advanced Research Project Agency (DARPA) and the European Commission. Standardizing the Web W3C is working to make the Web accessible to all users (despite differences in culture.How it Started The World Wide Web (WWW) began as a project at the European Organization for Nuclear Research (CERN). The French National Research Institute in Europe Keio University in Japan W3C Members Because the Web is so important (both in scope and in investment) that no single organization should have control over its future. W3C is hosted by three universities:    Massachusetts Institute of Technology in the U. W3C was created in 1994 as a collaboration between the Massachusetts Institute of Technology (MIT) and the European Organization for Nuclear Research (CERN).is now the Director of the World Wide Web Consortium (W3C).S. the Wireless Application Protocols (WAP) Forum and the Unicode Consortium.S. resources. Some well known members are:       IBM Microsoft America Online Apple Adobe Macromedia . with support from the U. W3C functions as a member organization. where Tim Berners-Lee developed a vision of the World Wide Web.the inventor of the World Wide Web . ability. and physical limitations) W3C also coordinates its work with many other standards organizations such as the Internet Engineering Task Force.

corporate users. research laboratories. The group obtains its input from companies and other organizations. standardized fashion (though the reality is less perfect). for a formal approval as a W3C Recommendation. HTML5 is a Revolution By Max On November 25. and governments. HTML5: the empowerment of open web technologies. and Opera to produce browsers that generally behave in a similar. But what makes HTML5 truly interesting is not just the list of technological advancements. HTML5 is a revolution for the open web. In general the Recommendation is submitted to the W3C membership and director. . telecommunications companies. or HTML5. W3C Recommendations The most important work done by the W3C is the development of Web specifications (called "Recommendations") that describe communication protocols (like HTML and XML) and other building blocks of the Web. Sun Microsystems The Full List of Member Organizations includes a variety of software vendors. and creates a Working Draft and finally a Proposed Recommendation. introduces many new features that make browsers more powerful and capable of providing modern web experiences. html5 “HTML5″ is a semi-buzzword that is thrown around quite a bit these days. This provides a convenient way for browser developers like Mozilla. academic institutions. and why does it matter? Technically. content providers. the term has a simple definition: HTML5 is the 5th revision of the HTML standard that Web Browsers use to display web pages. standards bodies. Microsoft. What exactly does it mean. Google. The 5th revision of the HTML standard. 2012 · Leave a Comment · In Codiqa. Each W3C Recommendation is developed by a work group consisting of members and invited experts.

you can build amazing mobile and desktop applications with HTML5 and open web technologies. . It’s this movement that excited us enough to build Codiqa and join the growing ecosystem of HTML5-based development tools. both of which are free. That. more companies and developers stand to gain through the greater adoption of HTML5 than with proprietary platforms like iOS.With HTML5. if you want to build traditional iOS apps. For example. our web browsers can do increasingly amazing things that were once the domain of locked-down proprietary platforms like iOS and Adobe Flash. developing for the web or mobile had to be done through proprietary systems. and not controlled by corporate interests. HTML5 is all about giving our open platforms more power to deliver increasingly amazing and complex products and experiences. We can access the camera on a mobile device. and with very open licenses. such as jQuery Mobile. All you need is a text editor and a browser. for $1500) and a $99/yr developer license just to build and release your app. If you were building Flash applications to provide animated content or stream video to a website. Looking into the future. we strongly believe that HTML5 and open web technologies will increasingly become the standard for mobile and desktop development. and products. We want to help move more mobile development over to HTML5 technologies and frameworks. investment and development is increasing for HTML5 tools. HTML5 is the Future As it stands. generally for free. get the user’s current location through GPS. you need a Mac (say. display video and play audio. or render complex 3D scenes. you had to purchase Adobe Flash Professional for $699. As such. all with open web technologies that we can all use. often for a decent cost. Today. services. Reducing Barriers to Entry Previously. in a way that is accessible to the largest number of people. We don’t recommend betting against the open web.

better form handling. a novice. Are you new to HTML5. and the use of the internet. HTML5 also includes new elements for better structure. we recommend the great HTML5 mobile framework jQuery Mobile which Codiqa is based on (our tool helps you visually build mobile apps with jQuery Mobile).01 are obsolete. To better handle today's internet use. and for media content. New Semantic/Structural Elements HTML5 offers new elements for better structure: Tag <article> <aside> <bdi> <command> Description Defines an article Defines content aside from the page content Isolates a part of text that might be formatted in a different direction from other text outside it Defines a command button that a user can invoke . or an expert? What exciting things has HTML5 enabled you to do. Once you’ve got the basics down. one of the best resources for really digging into HTML5 is Dive Into HTML5 by Mark Pilgrim. drawing. we recommend Dave Wood’s short HTML5 Tutorial.01 became a standard in 1999. never used. To get started with HTML5 development for mobile. Today. or what are you interested in doing? New Elements in HTML5 The internet. has changed a lot since HTML 4.Getting Started To get started with HTML5 as fast as possible. These elements are removed or re-written in HTML5. or not used the way they were intended. some elements in HTML 4.

<details> <dialog> <summary> <figure> <figcaption> <footer> <header> <hgroup> <mark> <meter> <nav> <progress> <ruby> <rt> <rp> Defines additional details that the user can view or hide Defines a dialog box or window Defines a visible heading for a <details> element Specifies self-contained content. Defines a caption for a <figure> element Defines a footer for a document or section Defines a header for a document or section Groups a set of <h1> to <h6> elements when a heading has multiple levels Defines marked/highlighted text Defines a scalar measurement within a known range (a gauge) Defines navigation links Represents the progress of a task Defines a ruby annotation (for East Asian typography) Defines an explanation/pronunciation of characters (for East Asian typography) Defines what to show in browsers that do not support ruby annotations HTML5 Audio HTML5 provides a standard for playing audio files. diagrams. . there has not been a standard for playing audio files on a web page. like illustrations. code listings. photos. etc. Audio on the Web Until now.

Chrome. like play.ogg" type="audio/ogg"> <source src="horse. <source> elements can link to different audio files. different browsers may have different plug-ins. Opera. Note: Internet Explorer 8 and earlier versions. </audio> The control attribute adds audio controls. pause.gif" alt="Smiley face" height="42" width="42"> . However. You should also insert text content between the <audio> and </audio> tags for browsers that do not support the <audio> element. Firefox. do not support the <audio> element. The browser will use the first recognized format. HTML5 Audio .mp3" type="audio/mpeg"> Your browser does not support the audio element. HTML <img> Tag Complete HTML Reference Example How to insert an image: <imgsrc="smiley. most audio files are played through a plug-in (like flash). HTML5 defines a new element which specifies a standard way to embed an audio file on a web page: the <audio> element. and volume. this is all you need: <audio controls> <source src="horse. and Safari support the <audio> element. Browser Support Internet Explorer 9+.How It Works To play an audio file in HTML5.Today. The <audio> element allows multiple <source> elements.

images are linked to HTML pages. they will behave as regular text fields. HTML5 Form Elements HTML5 New Form Elements HTML5 has the following new form elements:    <datalist> <keygen> <output> Note: Not all major browsers support all the new form elements. you can already start using them.Browser Support The <img> tag is supported in all major browsers. There can be at maximum one <base> element in a document. Note: Images are not technically inserted into an HTML page. HTML <base> Tag Definition and Usage The <base> tag specifies the base URL/target for all relative URLs in a document. . The <img> tag creates a holding space for the referenced image. Definition and Usage The <img> tag defines an image in an HTML page. The <img> tag has two required attributes: src and alt. and it must be inside the <head> element. If they are not supported. However.

Use the <input> element's list attribute to bind it together with a <datalist> element. two keys are generated. The <keygen> tag specifies a key-pair generator field in a form.HTML5 <datalist> Element The <datalist> element specifies a list of pre-defined options for an <input> element. Example An <input> element with pre-defined values in a <datalist>: <input list="browsers"> <datalist id="browsers"> <option value="Internet Explorer"> <option value="Firefox"> <option value="Chrome"> <option value="Opera"> <option value="Safari"> </datalist> HTML5 <keygen> Element The purpose of the <keygen> element is to provide a secure way to authenticate users. and the public key is sent to the server. Example A form with a keygen field: <form action="demo_keygen. The public key could be used to generate a client certificate to authenticate the user in the future. The private key is stored locally. The <datalist> element is used to provide an "autocomplete" feature on <input> elements. one private and one public. When the form is submitted. Users will see a drop-down list of pre-defined options as they input data.asp" method="get"> Username: <input type="text" name="usr_name"> Encryption: <keygen name="security"> <input type="submit"> </form> .

value=parseInt(a. Example Perform a calculation and show the result in an <output> element: <form oninput="x.value)+parseInt(b.value)">0 <input type="range" id="a" value="50">100 + <input type="number" id="b" value="50">= <output name="x" for="a b"></output> </form> .HTML5 <output> Element The <output> element represents the result of a calculation (like one performed by a script).

Sign up to vote on this title
UsefulNot useful