What is SVG?
SVG stands for Scalable Vector Graphics
SVG is used to define graphics for the Web
SVG is a W3C recommendation
The HTML <svg> Element
The HTML <svg> element is a container for SVG graphics.
SVG has several methods for drawing paths, boxes, circles, text, and graphic images.
Browser Support
The numbers in the table specify the first browser version that fully supports the <svg> element.
Element
<svg> 4.0 9.0 3.0 3.2 10.1
SVG Circle
Example
<!DOCTYPE html>
<html>
<body>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
</body>
</html>
SVG Rectangle
Example
<svg width="400" height="100">
<rect width="400" height="100" style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" />
</svg>
SVG Rounded Rectangle
Sorry, your browser does not support inline SVG.
Example
<svg width="400" height="180">
<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</svg>
SVG Star
Sorry, your browser does not support inline SVG.
Example
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>
SVG Logo
SVG Sorry, your browser does not support inline SVG.
Example
<svg height="130" width="500">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="50" y="86">SVG</text>
Sorry, your browser does not support inline SVG.
</svg>
Differences Between SVG and Canvas
SVG is a language for describing 2D graphics in XML.
Canvas draws 2D graphics, on the fly (with a JavaScript).
SVG is XML based, which means that every element is available within the SVG DOM. You
can attach JavaScript event handlers for an element.
In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are
changed, the browser can automatically re-render the shape.
Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the
browser. If its position should be changed, the entire scene needs to be redrawn, including any
objects that might have been covered by the graphic.
Comparison of Canvas and SVG
The table below shows some important differences between Canvas and SVG:
Canvas SVG
Resolution independent
Resolution dependent Support for event handlers
No support for event handlers Best suited for applications with large
Poor text rendering capabilities rendering areas (Google Maps)
You can save the resulting image Slow rendering if complex (anything
as .png or .jpg that uses the DOM a lot will be slow)
Well suited for graphic-intensive games Not suited for game applications
HTML5 Drag and Drop
Drag the W3Schools image into the rectangle.
Drag and Drop
Drag and drop is a very common feature. It is when you "grab" an object and drag it to a
different location.
In HTML5, drag and drop is part of the standard: Any element can be draggable.
Browser Support
The numbers in the table specify the first browser version that fully supports Drag and Drop.
API
Drag and Drop 4.0 9.0 3.5 6.0 12.0
HTML Drag and Drop Example
The example below is a simple drag and drop example:
Example
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="img_logo.gif" draggable="true"
ondragstart="drag(event)" width="336" height="69">
</body>
</html>
It might seem complicated, but lets go through all the different parts of a drag and drop event.
Make an Element Draggable
First of all: To make an element draggable, set the draggable attribute to true:
<img draggable="true">
What to Drag - ondragstart and setData()
Then, specify what should happen when the element is dragged.
In the example above, the ondragstart attribute calls a function, drag(event), that specifies what
data to be dragged.
The dataTransfer.setData() method sets the data type and the value of the dragged data:
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
In this case, the data type is "text" and the value is the id of the draggable element ("drag1").
Where to Drop - ondragover
The ondragover event specifies where the dragged data can be dropped.
By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent
the default handling of the element.
This is done by calling the event.preventDefault() method for the ondragover event:
event.preventDefault()
Do the Drop - ondrop
When the dragged data is dropped, a drop event occurs.
In the example above, the ondrop attribute calls a function, drop(event):
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Code explained:
Call preventDefault() to prevent the browser default handling of the data (default is open as link
on drop)
Get the dragged data with the dataTransfer.getData() method. This method will return any data
that was set to the same type in the setData() method
The dragged data is the id of the dragged element ("drag1")
Append the dragged element into the drop element
More Examples
Drag image back and forth
How to drag (and drop) an image back and forth between two <div> elements:
HTML5 Geolocation
The HTML Geolocation API is used to locate a user's position.
Locate the User's Position
The HTML Geolocation API is used to get the geographical position of a user.
Since this can compromise privacy, the position is not available unless the user approves it.
Note: Geolocation is most accurate for devices with GPS, like iPhone.
Browser Support
The numbers in the table specify the first browser version that fully supports Geolocation.
API
5.0 - 49.0 (http)
Geolocation 9.0 3.5 5.0 16.0
50.0 (https)
Note: As of Chrome 50, the Geolocation API will only work on secure contexts such as HTTPS.
If your site is hosted on an non-secure origin (such as HTTP) the requests to get the users
location will no longer function.
Using HTML Geolocation
The getCurrentPosition() method is used to return the user's position.
The example below returns the latitude and longitude of the user's position:
Example
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
Example explained:
Check if Geolocation is supported
If supported, run the getCurrentPosition() method. If not, display a message to the user
If the getCurrentPosition() method is successful, it returns a coordinates object to the function
specified in the parameter (showPosition)
The showPosition() function outputs the Latitude and Longitude
The example above is a very basic Geolocation script, with no error handling.
Handling Errors and Rejections
The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a
function to run if it fails to get the user's location:
Example
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
Displaying the Result in a Map
To display the result in a map, you need access to a map service, like Google Maps.
In the example below, the returned latitude and longitude is used to show the location in a
Google Map (using a static image):
Example
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
"+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
Google Map Script
How to show an interactive Google Map with a marker, zoom and drag options.
Location-specific Information
This page has demonstrated how to show a user's position on a map.
Geolocation is also very useful for location-specific information, like:
Up-to-date local information
Showing Points-of-interest near the user
Turn-by-turn navigation (GPS)
The getCurrentPosition() Method - Return Data
The getCurrentPosition() method returns an object on success. The latitude, longitude and
accuracy properties are always returned. The other properties are returned if available:
Property Returns
coords.latitude The latitude as a decimal number (always returned)
coords.longitude The longitude as a decimal number (always returned)
coords.accuracy The accuracy of position (always returned)
coords.altitude The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy The altitude accuracy of position (returned if available)
coords.heading The heading as degrees clockwise from North (returned if available)
coords.speed The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)
Geolocation Object - Other interesting Methods
The Geolocation object also has other interesting methods:
watchPosition() - Returns the current position of the user and continues to return updated
position as the user moves (like the GPS in a car).
clearWatch() - Stops the watchPosition() method.
The example below shows the watchPosition() method. You need an accurate GPS device to test
this (like iPhone):
Example
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
HTML5 Local Storage
HTML local storage; better than cookies.
What is HTML Local Storage?
With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request.
Local storage is more secure, and large amounts of data can be stored locally, without affecting
website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred
to the server.
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and
access the same data.
Browser Support
The numbers in the table specify the first browser version that fully supports Local Storage.
API
Web Storage 4.0 8.0 3.5 4.0 11.5
HTML Local Storage Objects
HTML local storage provides two objects for storing data on the client:
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session (data is lost when the browser tab is
closed)
Before using local storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted
when the browser is closed, and will be available the next day, week, or year.
Example
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Example explained:
Create a localStorage name/value pair with name="lastname" and value="Smith"
Retrieve the value of "lastname" and insert it into the element with id="result"
The example above could also be written like this:
// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
The syntax for removing the "lastname" localStorage item is as follows:
localStorage.removeItem("lastname");
Note: Name/value pairs are always stored as strings. Remember to convert them to another
format when needed!
The following example counts the number of times a user has clicked a button. In this code the
value string is converted to a number to be able to increase the counter:
Example
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";
The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores the data for
only one session. The data is deleted when the user closes the specific browser tab.
The following example counts the number of times a user has clicked a button, in the current
session:
Example
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
HTML5 Semantic Elements
Semantics is the study of the meanings of words and phrases in a language.
Semantic elements = elements with a meaning.
What are Semantic Elements?
A semantic element clearly describes its meaning to both the browser and the developer.
Examples of non-semantic elements: <div> and <span> - Tells nothing about its content.
Examples of semantic elements: <form>, <table>, and <article> - Clearly defines its content.
Browser Support
Yes Yes Yes Yes Yes
HTML5 semantic elements are supported in all modern browsers.
In addition, you can "teach" older browsers how to handle "unknown elements".
Read about it in HTML5 Browser Support.
New Semantic Elements in HTML5
Many web sites contain HTML code like: <div id="nav"> <div class="header"> <div
id="footer">
to indicate navigation, header, and footer.
HTML5 offers new semantic elements to define different parts of a web page:
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>
HTML5 <section> Element
The <section> element defines a section in a document.
According to W3C's HTML5 documentation: "A section is a thematic grouping of content,
typically with a heading."
A home page could normally be split into sections for introduction, content, and contact
information.
Example
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is....</p>
</section>
HTML5 <article> Element
The <article> element specifies independent, self-contained content.
An article should make sense on its own, and it should be possible to read it independently from
the rest of the web site.
Examples of where an <article> element can be used:
Forum post
Blog post
Newspaper article
Example
<article>
<h1>What Does WWF Do?</h1>
<p>WWF's mission is to stop the degradation of our planet's natural environment,
and build a future in which humans live in harmony with nature.</p>
</article>
Nesting <article> in <section> or Vice Versa?
The <article> element specifies independent, self-contained content.
The <section> element defines section in a document.
Can we use the definitions to decide how to nest those elements? No, we cannot!
So, on the Internet, you will find HTML pages with <section> elements containing <article>
elements, and <article> elements containing <sections> elements.
You will also find pages with <section> elements containing <section> elements, and <article>
elements containing <article> elements.
Example for a newspaper: The sport articles in the sport section, may have a technical section in
each article.
HTML5 <header> Element
The <header> element specifies a header for a document or section.
The <header> element should be used as a container for introductory content.
You can have several <header> elements in one document.
The following example defines a header for an article:
Example
<article>
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's natural environment,
and build a future in which humans live in harmony with nature.</p>
</article>
HTML5 <footer> Element
The <footer> element specifies a footer for a document or section.
A <footer> element should contain information about its containing element.
A footer typically contains the author of the document, copyright information, links to terms of
use, contact information, etc.
You may have several <footer> elements in one document.
Example
<footer>
<p>Posted by: Hege Refsnes</p>
<p>Contact information: <a href="mailto:someone@example.com">
someone@example.com</a>.</p>
</footer>
HTML5 <nav> Element
The <nav> element defines a set of navigation links.
Notice that NOT all links of a document should be inside a <nav> element. The <nav> element
is intended only for major block of navigation links.
Example
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
HTML5 <aside> Element
The <aside> element defines some content aside from the content it is placed in (like a sidebar).
The aside content should be related to the surrounding content.
Example
<p>My family and I visited The Epcot center this summer.</p>
<aside>
<h4>Epcot Center</h4>
<p>The Epcot Center is a theme park in Disney World, Florida.</p>
</aside>
HTML5 <figure> and <figcaption> Elements
The purpose of a figure caption is to add a visual explanation to an image.
In HTML5, an image and a caption can be grouped together in a <figure> element:
Example
<figure>
<img src="pic_mountain.jpg" alt="The Pulpit Rock" width="304" height="228">
<figcaption>Fig1. - The Pulpit Rock, Norway.</figcaption>
</figure>
The <img> element defines the image, the <figcaption> element defines the caption.
Why Semantic Elements?
With HTML4, developers used their own id/class names to style elements: header, top, bottom,
footer, menu, navigation, main, container, content, article, sidebar, topnav, etc.
This made it impossible for search engines to identify the correct web page content.
With the new HTML5 elements (<header> <footer> <nav> <section> <article>), this will
become easier.
According to the W3C, a Semantic Web: "Allows data to be shared and reused across
applications, enterprises, and communities."
Semantic Elements in HTML5
Below is an alphabetical list of the new semantic elements in HTML5.
The links go to our complete HTML5 Reference.
Tag Description
<article> Defines an article
<aside> Defines content aside from the page content
<details> Defines additional details that the user can view or hide
<figcaption> Defines a caption for a <figure> element
Specifies self-contained content, like illustrations, diagrams, photos, code listings,
<figure>
etc.
<footer> Defines a footer for a document or section
<header> Specifies a header for a document or section
<main> Specifies the main content of a document
<mark> Defines marked/highlighted text
<nav> Defines navigation links
<section> Defines a section in a document
<summary> Defines a visible heading for a <details> element
<time> Defines a date/time
HTML5 New Elements
New Elements in HTML5
Below is a list of the new HTML5 elements, and a description of what they are used for.
New Semantic/Structural Elements
HTML5 offers new elements for better document structure:
Tag Description
<article> Defines an article in the document
<aside> Defines content aside from the page content
<bdi> Defines a part of text that might be formatted in a different direction from other text
<details> Defines additional details that the user can view or hide
<dialog> Defines a dialog box or window
<figcaption> Defines a caption for a <figure> element
<figure> Defines self-contained content, like illustrations, diagrams, photos, code listings, etc.
<footer> Defines a footer for the document or a section
<header> Defines a header for the document or a section
<main> Defines the main content of a document
<mark> Defines marked or highlighted text
<menuitem> Defines a command/menu item that the user can invoke from a popup menu
<meter> Defines a scalar measurement within a known range (a gauge)
<nav> Defines navigation links in the document
<progress> Defines the progress of a task
<rp> Defines what to show in browsers that do not support ruby annotations
<rt> Defines an explanation/pronunciation of characters (for East Asian typography)
<ruby> Defines a ruby annotation (for East Asian typography)
<section> Defines a section in the document
<summary> Defines a visible heading for a <details> element
<time> Defines a date/time
<wbr> Defines a possible line-break
Read more about HTML5 Semantics.
New Form Elements
Tag Description
<datalist> Defines pre-defined options for input controls
<keygen> Defines a key-pair generator field (for forms)
<output> Defines the result of a calculation
Read all about old and new form elements in HTML Form Elements.
New Input Types
New Input Types New Input Attributes
color autocomplete
date autofocus
datetime form
datetime-local formaction
email formenctype
month formmethod
number formnovalidate
range formtarget
search height and width
tel list
time min and max
url multiple
week pattern (regexp)
placeholder
required
step
Learn all about old and new input types in HTML Input Types.
Learn all about input attributes in HTML Input Attributes.
HTML5 - New Attribute Syntax
HTML5 allows four different syntaxes for attributes.
This example demonstrates the different syntaxes used in an <input> tag:
Type Example
Empty <input type="text" value="John" disabled>
Unquoted <input type="text" value=John>
Double-quoted <input type="text" value="John Doe">
Single-quoted <input type="text" value='John Doe'>
In HTML5, all four syntaxes may be used, depending on what is needed for the attribute.
HTML5 Graphics
Tag Description
<canvas> Draw graphics, on the fly, via scripting (usually JavaScript)
<svg> Draw scalable vector graphics
Read more about HTML5 Canvas.
Read more about HTML5 SVG.
New Media Elements
Tag Description
<audio> Defines sound content
<embed> Defines containers for external applications (like plug-ins)
<source> Defines sources for <video> and <audio>
<track> Defines tracks for <video> and <audio>
<video> Defines video or movie content