HTML 5 New Elements 105 – Web Development

Hello!! everyone here we back again with new topics of HTML 5 Tutorial. This is the last article of the HTML 5 Tutorial Series.

If you missed the previous articles then check once HTML5 Tutorial 104.

So, lets begin…

The topics which we will covers in this tutorial:-

  • Application Cache
  • Web Workers
  • SSE
  • Geolocation
  • Drag & Drop
  • New Input Types

HTML5 Application Cache

html 5

HTML 5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.

Application cache gives an application three advantages:

  1. The offline browsing – users can use the application when they’re offline
  2. Speed – cached resources load faster
  3. Reduced server load – the browser will only download updated/changed resources from the server

HTML Cache Manifest Example

The example below shows an HTML document with a cache manifest (for offline browsing):

For example

<!DOCTYPE HTML>
<html manifest="demo.appcache">

<body>
The content of the document......
</body>

</html>

The Manifest File

The manifest file is a simple text file, that tells the browser what to cache (and what to never cache).

The manifest file has three sections:

  • CACHE MANIFEST – Thr files listed under this header will be cached after they are downloaded for the first time
  • NETWORK – Files listed under this header require a connection to the server, and will never be cached
  • FALLBACK – Files listed under this header specifies fallback pages if a page is inaccessible

CACHE MANIFEST

The first line, CACHE MANIFEST, is required:

CACHE MANIFEST
/theme.css
/logo.gif
/main.js

The manifest file above lists three sources: a CSS file, a GIF image, and a JavaScript file. On the manifest file’s loading time, the browser will download the three files from the root directory of the web site. Then, whenever the user is not connected to the internet, the resources will not be unavailable.

NETWORK

The NETWORK section below defines that the file “login.asp” should never be cached, and will not be available offline:

NETWORK:
login.asp

An asterisk can be used to indicate that all other resources/files require an internet connection.

FALLBACK

The FALLBACK division below specifies that “offline.html” will be served in place of all files in the /HTML/ catalog, in case an internet connection cannot be verified.

FALLBACK:
/html/ /offline.html

Note: The first URL is the resource, the second is the fallback.

Web Workers

html 5

Web Workers initializes with the URL of a JavaScript file, that contains the code the worker will execute. This code sets event listeners and communicates with the script that spawned it from the main page. Following is the simple syntax −

var worker = new Worker('bigLoop.js');

If the defined javascript file exists, the browser will spawn a new worker thread, downloaded asynchronously.

Also if the path to your worker returns a 404 error, the worker will fail silently.

If your application has multiple carrying JavaScript files, you can import them importScripts() method, which takes file name(s) as argument separated by a comma as follows −

importScripts("helper.js", "anotherHelper.js");

Once the Web Worker is created, communication between a web worker and its parent page is done using the postMessage() method. Depending on our browser/version, postMessage() can accept either a string or JSON object as its single argument.

The Message is passed by Web Worker is accessed using onmessage event on the main page. Now let us write our bigLoop example using the Web Worker. Below is the main page (hello.htm) which will spawn a web worker to execute the loop and to return the final value of variables 

HTML Web Workers Example

The example below creates a simple web worker that count numbers in the background:

<!DOCTYPE html>
<html>
<body>

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

<p><strong>Note:</strong> Internet Explorer 9 and earlier versions do not support Web Workers.</p>

<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, your browser does not support Web Workers...";
  }
}

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

</body>
</html>

HTML5 SSE

HTML5 server-sent event

The HTML5 server-sent event is a new way for the web pages to communicating with the webserver. It is also possible with the XMLHttpRequest object that lets your JavaScript code make a request to the webserver, but it’s a one-for-one exchange — that means once the webserver provides its response, the communication is over. XMLHttpRequest object is the core operation of all Ajax operations.

However, there are some places where web pages needed a longer-term connection to the webserver. A common example is stock quotes on finance websites where the price is updated automatically. Another example is the news ticker showing on various media websites.

html5

You can also create such things with the HTML5 server-sent events. It allows a web page to hold an open connection to a web server so that the webserver can send a new response automatically at any time, there’s no need to reconnect, and run the same server script from scratch over and over again

Sending Messages with a Server Script

Let’s create a PHP file and named “server_time.php” and type the next script into it. It will simply report the current time of the web server’s built-in clock at regular intervals.

For example

<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
 
// Get the current time on server
$currentTime = date("h:i:s", time());
 
// Send it in a message
echo "data: " . $currentTime . "\n\n";
flush();
?>

First two lines of the PHP script sets two important headers. First, it sets the MIME type to text/event-stream, which is needed by the server-side event standard. The second line tells the webserver to turn off caching otherwise the output of your script may be cached.

Every message sent through HTML5 server-sent events must start with the text data followed by the actual message text and the new line character sequence (\n\n).

And then, you have to use the PHP flush() function to make sure that the data will be sent right away, rather than buffered until the PHP code is complete.

HTML5 Geolocation

html 5

The HTML5 geolocation characteristic lets you find out the geographic coordinates (latitude and longitude numbers) of your website’s visitor’s current location.

This HTML feature helps provide a better browsing experience to the site visitor. For example, you can return the search results that are physically close to the user’s location.

Finding a Visitor’s Coordinates

Getting the position knowledge of the site visitor using the HTML5 Geolocation API is very simple. It is utilized by the three methods that are packed into -the navigator.geolocation object — getCurrentPosition(), watchPosition() and clearWatch().

Following is a simple model of geolocation that displays your current position. But first, we need to agree to let the browser tell the webserver about our position.

For example

   var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': <YOURLATLNGRESPONSEFROMGEO>}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var loc = getCountry(results);
                }
            }
        });

    function getCountry(results)
    {
        for (var i = 0; i < results[0].address_components.length; i++)
        {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(shortname))
            {
                return shortname;
            }
            else
            {
                return longname;
            }
        }
    }

}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/\s/gi, '').length < 1;
}

HTML5 Drag & Drop

html 5

The HTML5 drag and drop characteristic allows the user to drag and drop an element to another location. The drop location may be or may not be a different application. While dragging an element, a translucent representation of the element is to follow the mouse pointer.

Drag and Drop Events

The drag-and-drop event of HTML uses the DOM event model and drag events inherited from mouse events. A typical drag operation starts when a user selects a draggable element, drags the element to a droppable element, and then releases the dragged element.

The following table provides you a brief overview of all the drag and drop events.

EventDescription
ondragstartFires when the user starts dragging an element.
ondragenterIt occurs when a draggable element is first moved into a drop listener.
ondragoverFires when the user drags an element over a drop listener.
ondreagleaveIt occurs when the user drags an element out of drop listener.
ondragFires when the user drags an element anywhere; fires constantly but can give X and Y coordinates of the mouse cursor.
ondropIt occurs when the user drops an element into a drop listener successfully.
ondragendFires when the drag action is complete, whether it was successful or not. This event is not fired when dragging a file to the browser from the desktop.

This section is primarily a review of the basic steps to add drag-and-drop functionality to an application.

Making an element draggable needs adding the draggable property and the ondragstart global event handler, as shown in the following code sample:

<script>
  function dragstart_handler(ev) {
    // Add the target element's id to the data transfer object
    ev.dataTransfer.setData("text/plain", ev.target.id);
  }

  window.addEventListener('DOMContentLoaded', () => {
    // Get the element by id
    const element = document.getElementById("p1");
    // Add the ondragstart event listener
    element.addEventListener("dragstart", dragstart_handler);
  });
</script>

<p id="p1" draggable="true">This element is draggable.</p>

Define the drag image

By default, the browser supplies an image that is appeared beside the pointer during a drag operation. But, an application may define a custom image with the setDragImage() method, as shown in the following mentioned example.

function dragstart_handler(ev) {
  // Create an image and then use it for the drag image.
  // NOTE: change "example.gif" to a real image URL or the image 
  // will not be created and the default drag image will be used.
  let img = new Image(); 
  img.src = 'example.gif'; 
  ev.dataTransfer.setDragImage(img, 10, 10);
}

HTML5 New Input Types

html 5

The <input> element is used within a <form></form> element and defines an input field where the user can enter data.

HTML5 introduces the following new <input> types:

  • color : for input fields with colors, i.e. color picker/ color selector
  • date : allows the user to select data, i.e. date picker with calendar
  • datetime: allows the user to select a date and time (
  • datetime-local
  • email: for input fields that should contain an e-mail address.
  • month : allows the user to select a month and year. I.e. date picker with month and year only
  • number : for a numeric value input only, you can also set restrictions on acceptable numbers using one of the following <input> attributes: max for max allowed value, min for the min allowed value, step for the number interval and value for setting the default value.

For example: <input type="number" min="1" max="5"/>

Demo result

  • range: It should contain a value from a range of numbers. In the same way, as with the number type, you can use the following <input> attributes to specify the range: max for max allowed value, min for the min allowed value, step for the number interval and value for setting the default value.

For example<input type="range" min="1" max="5"/>

Demo result

  • search: for search fields
  • tel: a field that is intended to be used for entering a phone numbers
  • time : for input field for entering time via up/down buttons
  • url : for input fields that should contain a URL address
  • week: allows the user to select a week and year.

Input Type Color

The color input type allows the user to choose a color from a color picker, and it returns the color value in hexadecimal format (#rrggbb). If you don’t specify a value, the default is #000000, which is black.

Let’s try out the following example to understand how it basically works:

For example

<form>
    <label for="mycolor">Select Color:</label>
    <input type="color" value="#00ff00" id="mycolor">
</form>

Input Type URL

The url input type can be used for entering URL’s or web addresses.

Here, we can use the multiple attribute to enter more than one URL. And if an attribute is a specified browser will automatically carry out validation to ensure that only text that matches the standard format for URLs is entered into the input box. Let’s see how this works:

For example

<form>
    <label for="myurl">Enter Website URL:</label>
    <input type="url" id="myurl" required>
</form>

This is the last part of this HTML Tutorial. I hope this content is helpful for those who want to learn HTML or want to start Web Development.

After HTML now we are moving to CSS is played a very important role in the Web Development cycle.

html 5, html 5, html 5, html 5, html 5, html 5

7 thoughts on “HTML 5 New Elements 105 – Web Development

  1. Asking questions are really pleasant thing if you are not understanding something completely, but this post provides
    good understanding even.

Leave a Reply

Your email address will not be published. Required fields are marked *