Skip to content

Instantly share code, notes, and snippets.

@vishnu-saini
Last active August 11, 2018 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishnu-saini/834db4832b44522977797fd5e0cb050d to your computer and use it in GitHub Desktop.
Save vishnu-saini/834db4832b44522977797fd5e0cb050d to your computer and use it in GitHub Desktop.

HTML5

What is New in HTML5

The DOCTYPE declaration for HTML5 is very simple:

<!DOCTYPE html> 

The character encoding (charset) declaration is also very simple:

<meta charset="UTF-8">

New HTML5 Elements

The most interesting new HTML5 elements are:

  • New semantic elements like <header>, <footer>, <article>, and <section>.
  • New attributes of form elements like number, date, time, calendar, and range.
  • New graphic elements: <svg> and <canvas>.
  • New multimedia elements: <audio> and <video>.
  • HTML Geolocation
  • HTML Drag and Drop
  • HTML Local Storage
  • HTML Application Cache
  • HTML Web Workers
  • HTML SSE

Define Semantic Elements as Block Elements

HTML5 defines eight new semantic elements. All these are block-level elements. To secure correct behavior in older browsers, you can set the CSS display property for these HTML elements to block:

header, section, footer, aside, nav, main, article, figure {
    display: block; 
}

Add New Elements to HTML

You can also add new elements to an HTML page with a browser trick.

<script>document.createElement("myHero")</script>
<style>
myHero {
    display: block;
    background-color: #dddddd;
    padding: 50px;
    font-size: 30px;
} 
</style> 

<myHero>My Hero Element</myHero>

New Semantic/Structural Elements

  • <article> Defines an article in a document
  • <aside> Defines content aside from the page content
  • <dialog> Defines a dialog box or window
  • <figcaption> Defines a caption for a element
  • <figure> Defines self-contained content
  • <footer> Defines a footer for a document or section
  • <header> Defines a header for a document or section
  • <main> Defines the main content of a document
  • <mark> Defines marked/highlighted text
  • <nav> Defines navigation links
  • <progress> Represents the progress of a task
  • <section> Defines a section in a document
  • <summary> Defines a visible heading for a <details> element
  • <time> Defines a date/time

HTML5 Canvas

  • The HTML element is used to draw graphics, on the fly, via JavaScript.
  • The element is only a container for graphics. You must use JavaScript to actually draw the graphics.
  • Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Canvas Examples:

<canvas id="myCanvas" width="200" height="100"></canvas>

//Draw a Line with javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

SVG

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 is a container for SVG graphics. SVG has several methods for drawing paths, boxes, circles, text, and graphic images.

Example Circle

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</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 dependent Resolution independent
No support for event handlers Support for event handlers
Poor text rendering capabilities Best suited for applications with large rendering areas (Google Maps)
You can save the resulting image as .png or .jpg Slow rendering if complex (anything that uses the DOM a lot will be slow)
Well suited for graphic-intensive games Not suited for game applications

HTML Google Maps

<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?callback=myMap"></script>
<script>
    function myMap() {
        var mapOptions = {
            center: new google.maps.LatLng(51.5, -0.12),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.HYBRID
        }
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    }
</script>
</head>
<body>
    <h1>My First Google Map</h1>
    <div id="map" style="width:400px;height:400px">My map will go here</div>
</body>
<html>

web workers

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Create Web Worker File - demo_workers.js

var i = 0;

function timedCount() {
    i = i + 1;
    postMessage(i);
    setTimeout("timedCount()",500);
}

timedCount();

Using by webworker

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>

<script>
var w;
function startWorker() {
    if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
    }
}

function stopWorker() { 
    w.terminate();
    w = undefined;
}
</script>
</body>
</html>

< !DOCTYPE>

The Doctype does two things.

  • It identifies which dialect of HTML you're using.
  • It controls whether the browsers uses "standards" or "quirks" mode to render the document.

If there is no doctype, or there's an unrecognized one, then it uses "quirks" mode and interprets the document as best it can. If there IS a doctype, and it recognizes it, then it follows the standards. The results of the rendering can vary depending on how it interprets the document.

The < !DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in. AND The < !DOCTYPE> tag does not have an end tag and It is not case sensitive. The < !DOCTYPE> declaration must be the very first thing in HTML5 document, before the tag. As In HTML 4.01, all < ! DOCTYPE > declarations require a reference to a Document Type Definition (DTD), because HTML 4.01 was based on Standard Generalized Markup Language (SGML). Where as HTML5 is not based on SGML, and therefore does not require a reference to a Document Type Definition (DTD).

HTML5 Geolocation

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.

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:

<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>

HTML5 Drag and Drop

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.

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>

HTML5 Web Storage

With web 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. Web 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.

Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

HTML Web Storage Objects

HTML web 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)
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
//remove
localStorage.removeItem("lastname");

input type attributes in HTML5

  • tel : If you want to make text box to accept telephone numbers.
  • search : Want to make text box as search engine box.
  • url : For URL validation set the type as “url”
  • email : If you want to create a HTML text with email validation
  • datetime A date and/or time
  • date : If you want to show calendar dialog box.
  • month A month
  • week A week
  • time : What to only take time input.
  • datetime-local : If you want to show calendar with local time.
  • number A number.
  • range : If you want to display a range control you can use type as range
  • color : If you want to show color picker dialog box

input attributes

  • placeholder Specifies a short hint that describes the expected value of an input field.
  • size : The size attribute specifies the width (in characters) for the input field:
  • maxlength : The maxlength attribute specifies the maximum allowed length for the input field:
  • min : The min attribute specify the minimum values for an input element
  • max : The max attribute specify the maximum values for an input element
  • step : The step attribute specifies the legal number intervals for an element.
  • readonly : The readonly attribute specifies that the input field is read only (cannot be changed):
  • disabled : The disabled attribute specifies that the input field is disabled.
  • autofocus : The autofocus attribute specifies that the input field should automatically get focus when the page loads.

some important attribute

  • title : The value of the title attribute will be displayed as a tooltip when you mouse over
  • alt : The alt attribute specifies an alternative text to be used, when an image cannot be displayed.
  • multiple : The multiple attribute specifies that the user is allowed to enter more than one value in the input element like in file input or select input

Drawbacks of cookies

Cookies have 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.

HTML5 Autocomplete - HTML Tag

Datalist element in HTML 5 helps to provide autocomplete feature in a textbox as shown below.

<input list="browsers">

<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

HTML5 backward compatibility

Yes! HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers. It is suggested to detect support for individual HTML5 features using a few lines of JavaScript.

Quirks Mode and Standards Mode

In the old days of the web, pages were typically written in two versions: One for Netscape Navigator, and one for Microsoft Internet Explorer. When the web standards were made at W3C, browsers could not just start using them, as doing so would break most existing sites on the web. Browsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites.

In HTML5, the only purpose of the DOCTYPE is to activate full standards mode. Older versions of the HTML standard gave additional meaning to the DOCTYPE, but no browser has ever used the DOCTYPE for anything other than switching between quirks mode and standards mode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment