티스토리 뷰

HTML5 Tutorial

HTML5 is the latest and most enhanced version of HTML. Technically, HTML is not a programming language, but rather a mark up language.

Overview

The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears.

Browser Support

The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.

The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.

New Features

HTML5 introduces a number of new elements and attributes that helps in building a modern website. Following are great features introduced in HTML5.

  • New Semantic Elements − These are like <header>, <footer>, and <section>.
  • Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> 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 events which flow from web server to the web browsers and they are called Server-Sent Events (SSE).
  • Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript.
  • Audio & Video − You can embed audio or video on your web pages without resorting to third-party plugins.
  • Geolocation − Now visitors can choose to share their physical location with your web application.
  • Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics.
  • Drag and drop − Drag and drop the items from one location to another location on a the same webpage.

Syntax

HTML5 is coming with lots of flexibility and would support the followings −

  • Uppercase tag names.
  • Quotes are optional for attributes.
  • Attribute values are optional.
  • Closing empty elements are optional.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <script src="scriptfile.js"></script>
    <link rel="stylesheet" href="stylefile.css">
  </head>
  <body>
    <h1></h1>
  </body>
</html>

HTML5 Elements

HTML5 tag names are case insensitive and may be written in all uppercase or mixed case, although the most common convention is to stick with lower case.

HTML5 Attributes

HTML5 attributes are case insensitive and may be written in all upper case or mixed case, although the most common convention is to stick with lower case.

HTML5 Document

The following tags have been introduced for better structure −

  • section − This tag represents a generic document or application section. It can be used together with h1-h6 to indicate the document structure.
  • article − This tag represents an independent piece of content of a document, such as a blog entry or newspaper article.
  • aside − This tag represents a piece of content that is only slightly related to the rest of the page.
  • header − This tag represents the header of a section.
  • footer − This tag represents a footer for a section and can contain information about the author, copyright information, etc.
  • nav − This tag represents a section of the document intended for navigation.
  • dialog − This tag can be used to mark up a conversation.
  • figure − This tag can be used to associate a caption together with some embedded content, such as a graphic or video.

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

<!DOCTYPE html>
<html>

   <head>
      <meta charset="utf-8">
      <title>...</title>
   </head>
	
   <body>
      <header>...</header>
      <nav>...</nav>
		
      <article>
         <section>
            ...
         </section>
      </article>
		
      <aside>...</aside>
      <figure>...</figure> 
      <footer>...</footer>
      
   </body>
</html>

Attributes

Standard Attributes

The attributes listed below are supported by almost all the HTML 5 tags.

AttributeOptionsFunction
accesskeyUser DefinedSpecifies a keyboard shortcut to access an element.
alignright, left, centerHorizontally aligns tags
backgroundURLPlaces an background image behind an element
bgcolornumeric, hexidecimal, RGB valuesPlaces a background color behind an element
classUser DefinedClassifies an element for use with Cascading Style Sheets.
contenteditabletrue, falseSpecifies if the user can edit the element's content or not.
contextmenuMenu idSpecifies the context menu for an element.
data-XXXXUser DefinedCustom attributes. Authors of a HTML document can define their own attributes. Must start with "data-".
draggabletrue,false, autoSpecifies whether or not a user is allowed to drag an element.
heightNumeric ValueSpecifies the height of tables, images, or table cells.
hiddenhiddenSpecifies whether element should be visible or not.
idUser DefinedNames an element for use with Cascading Style Sheets.
itemList of elementsUsed to group elements.
itempropList of itemsUsed to group items.
spellchecktrue, falseSpecifies if the element must have it's spelling or grammar checked.
styleCSS Style sheetSpecifies an inline style for an element.
subjectUser define idSpecifies the element's corresponding item.
tabindexTab numberSpecifies the tab order of an element.
titleUser Defined"Pop-up" title for your elements.
valigntop, middle, bottomVertically aligns tags within an HTML element.
widthNumeric ValueSpecifies the width of tables, images, or table cells.

Custom Attributes

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

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

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

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

Events

When a user visit your website, they do things like click on text and images and given links, hover over things etc. These are examples of what JavaScript calls events.

AttributeValueDescription
offlinescriptTriggers when the document goes offline
onabortscriptTriggers on an abort event
onafterprintscriptTriggers after the document is printed
onbeforeonloadscriptTriggers before the document loads
onbeforeprintscriptTriggers before the document is printed
onblurscriptTriggers when the window loses focus
oncanplayscriptTriggers when media can start play, but might has to stop for buffering
oncanplaythroughscriptTriggers when media can be played to the end, without stopping for buffering
onchangescriptTriggers when an element changes
onclickscriptTriggers on a mouse click
oncontextmenuscriptTriggers when a context menu is triggered
ondblclickscriptTriggers on a mouse double-click
ondragscriptTriggers when an element is dragged
ondragendscriptTriggers at the end of a drag operation
ondragenterscriptTriggers when an element has been dragged to a valid drop target
ondragleavescriptTriggers when an element leaves a valid drop target
ondragoverscriptTriggers when an element is being dragged over a valid drop target
ondragstartscriptTriggers at the start of a drag operation
ondropscriptTriggers when dragged element is being dropped
ondurationchangescriptTriggers when the length of the media is changed
onemptiedscriptTriggers when a media resource element suddenly becomes empty.
onendedscriptTriggers when media has reach the end
onerrorscriptTriggers when an error occur
onfocusscriptTriggers when the window gets focus
onformchangescriptTriggers when a form changes
onforminputscriptTriggers when a form gets user input
onhaschangescriptTriggers when the document has change
oninputscriptTriggers when an element gets user input
oninvalidscriptTriggers when an element is invalid
onkeydownscriptTriggers when a key is pressed
onkeypressscriptTriggers when a key is pressed and released
onkeyupscriptTriggers when a key is released
onloadscriptTriggers when the document loads
onloadeddatascriptTriggers when media data is loaded
onloadedmetadatascriptTriggers when the duration and other media data of a media element is loaded
onloadstartscriptTriggers when the browser starts to load the media data
onmessagescriptTriggers when the message is triggered
onmousedownscriptTriggers when a mouse button is pressed
onmousemovescriptTriggers when the mouse pointer moves
onmouseoutscriptTriggers when the mouse pointer moves out of an element
onmouseoverscriptTriggers when the mouse pointer moves over an element
onmouseupscriptTriggers when a mouse button is released
onmousewheelscriptTriggers when the mouse wheel is being rotated
onofflinescriptTriggers when the document goes offline
onoinescriptTriggers when the document comes online
ononlinescriptTriggers when the document comes online
onpagehidescriptTriggers when the window is hidden
onpageshowscriptTriggers when the window becomes visible
onpausescriptTriggers when media data is paused
onplayscriptTriggers when media data is going to start playing
onplayingscriptTriggers when media data has start playing
onpopstatescriptTriggers when the window's history changes
onprogressscriptTriggers when the browser is fetching the media data
onratechangescriptTriggers when the media data's playing rate has changed
onreadystatechangescriptTriggers when the ready-state changes
onredoscriptTriggers when the document performs a redo
onresizescriptTriggers when the window is resized
onscrollscriptTriggers when an element's scrollbar is being scrolled
onseekedscriptTriggers when a media element's seeking attribute is no longer true, and the seeking has ended
onseekingscriptTriggers when a media element's seeking attribute is true, and the seeking has begun
onselectscriptTriggers when an element is selected
onstalledscriptTriggers when there is an error in fetching media data
onstoragescriptTriggers when a document loads
onsubmitscriptTriggers when a form is submitted
onsuspendscriptTriggers when the browser has been fetching media data, but stopped before the entire media file was fetched
ontimeupdatescriptTriggers when media changes its playing position
onundoscriptTriggers when a document performs an undo
onunloadscriptTriggers when the user leaves the document
onvolumechangescriptTriggers when media changes the volume, also when volume is set to "mute"
onwaitingscriptTriggers when media has stopped playing, but is expected to resume

Web Forms 2.0

The <input> element in HTML5

Apart from the above mentioned attributes, HTML5 input elements introduced several new values for the type attribute. These are listed below.

S.No.Type & Description
1datetime: A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC.
2datetime-local: A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information.
3date: A date (year, month, day) encoded according to ISO 8601.
4month: A date consisting of a year and a month encoded according to ISO 8601.
5week: A date consisting of a year and a week number encoded according to ISO 8601.
6time: A time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601.
7number: This accepts only numerical value. The step attribute specifies the precision, defaulting to 1.
8range: The range type is used for input fields that should contain a value from a range of numbers.
9email: This accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in email@example.com format.
10url: This accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format.

The placeholder attribute

HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provides a hint to the user of what can be entered in the field. The place holder text must not contain carriage returns or line-feeds.

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.

<input type="text" name="search" autofocus/>

The required attribute

Now you do not need to have javascript for client side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value −

<input type="text" name="search" required/>

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 rendered by an SVG viewer.

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

Embeding SVG in HTML5

HTML5 allows embeding SVG directly using <svg>...</svg> tag which has following simple syntax −

<style>
  #svgelem {
    position: relative;
    left: 50%;
    -webkit-transform: translateX(-20%);
    -ms-transform: translateX(-20%);
    transform: translateX(-20%);
  }
</style>
...
<svg id="svgelem" height="200" xmlns="http://www.w3.org/2000/svg">
  <circle id="redcircle" cx="50" cy="50" r="50" fill="red" />
</svg>

MathML

MathML Examples

Following is a valid HTML5 document with MathML −

<math xmlns="http://www.w3.org/1998/Math/MathML">
  <mrow>
    <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>
  </mrow>
</math>

Web Storage

HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and to overcome following drawbacks.

  • Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data.
  • Cookies are included with every HTTP request, thereby sending data unencrypted over the internet.
  • Cookies are limited to about 4 KB of data . Not enough to store required data.

The two storage's are session storage and local storage and they would be used to handle different situations.

The latest versions of pretty much every browser supports HTML5 Storage including Internet Explorer.

Session Storage

HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window i.e session and as soon as you close the window, session would be lost.

Local Storage

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

Delete Web Storage

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

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

  // Reset number of hits.
  if( localStorage.hits ){
    localStorage.hits = Number(localStorage.hits) +1;
  }

  else{
    localStorage.hits = 1;
  }
  document.write("Total Hits :" + localStorage.hits );

</script>

Web SQL Database

Server Sent Events

WebSocket

Canvas

HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.

<style>
  #mycanvas{border:1px solid red;}
</style>
...
<canvas id="mycanvas" width="100" height="100"></canvas>

The Rendering Context

The<canvas> is initially blank, and to display something, a script first needs to access the rendering context and draw on it.

The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.

Following is the code to get required context along with a check if your browser supports <canvas>element −

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

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

else {   
   // canvas-unsupported code here 
}  

Audio & Video

Embedding Video

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. But most 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 type and many other attributes. A video element allows multiple source elements and browser will use the first recognized format −

<video  width="300" height="200" controls autoplay>
  <source src="/html5/foo.ogg" type="video/ogg" />
  <source src="/html5/foo.mp4" type="video/mp4" />
  Your browser does not support the video element.
</video>

Video Attribute Specification

The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities of the control −

AttributeDescription
autoplayThis boolean attribute if specified, the video will automatically begin to play back as soon as it can do so without stopping to finish loading the data.
autobufferThis boolean attribute if specified, the video will automatically begin buffering even if it's not set to automatically play.
controlsIf this attribute is present, it will allow the user to control video playback, including volume, seeking, and pause/resume playback.
heightThis attribute specifies the height of the video's display area, in CSS pixels.
loopThis boolean attribute if specified, will allow video automatically seek back to the start after reaching at the end.
preloadThis attribute specifies that the video will be loaded at page load, and ready to run. Ignored if autoplay is present.
posterThis is a URL of an image to show until the user plays or seeks.
srcThe URL of the video to embed. This is optional; you may instead use the element within the video block to specify the video to embed
widthThis attribute specifies the width of the video's display area, in CSS pixels.

Embedding Audio

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

You can use <source> tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format −

<audio controls autoplay>
  <source src="/html5/audio.ogg" type="audio/ogg" />
  <source src="/html5/audio.wav" type="audio/wav" />
  Your browser does not support the audio element.
</audio>

Audio Attribute Specification

The HTML5 audio tag can have a number of attributes to control the look and feel and various functionalities of the control:

AttributeDescription
autoplayThis boolean attribute if specified, the audio will automatically begin to play back as soon as it can do so without stopping to finish loading the data.
autobufferThis boolean attribute if specified, the audio will automatically begin buffering even if it's not set to automatically play.
controlsIf this attribute is present, it will allow the user to control audio playback, including volume, seeking, and pause/resume playback.
loopThis boolean attribute if specified, will allow audio automatically seek back to the start after reaching at the end.
preloadThis attribute specifies that the audio will be loaded at page load, and ready to run. Ignored if autoplay is present.
srcThe URL of the audio to embed. This is optional; you may instead use the element within the video block to specify the video to embed

Handling Media Events

The HTML5 audio and video tag can have a number of attributes to control various functionalities of the control using Javascript −

EventDescription
abortThis event is generated when playback is aborted.
canplayThis event is generated when enough data is available that the media can be played.
endedThis event is generated when playback completes.
errorThis event is generated when an error occurs.
loadeddataThis event is generated when the first frame of the media has finished loading.
loadstartThis event is generated when loading of the media begins.
pauseThis event is generated when playback is paused.
playThis event is generated when playback starts or resumes.
progressThis event is generated periodically to inform the progress of the downloading the media.
ratechangeThis event is generated when the playback speed changes.
seekedThis event is generated when a seek operation completes.
seekingThis event is generated when a seek operation begins.
suspendThis event is generated when loading of the media is suspended.
volumechangeThis event is generated when the audio volume changes.
waitingThis event is generated when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek).

Configuring Servers for Media Type

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

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

Geolocation

Microdata

Global Attributes

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

AttributeDescription
itemscopeThis 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.
itemtypeThis attribute is a valid URL which defines the item and provides the context for the properties.
itemidThis attribute is global identifier for the item.
itempropThis attribute defines a property of the item.
itemrefThis attribute gives a list of additional elements to crawl to find the name-value pairs of the item.

Drag and Drop

Web Workers

Indexed DB

Web Messaging

CORS

Web RTC


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday