Friday, March 29, 2024

Discover HTML5 Features, Code and Elements

Top HTML5 Features: Simplified Script Tags, Autofocus, and More

A couple of years after the launch of HTML5, we went back and reflected on how HTML5 has changed the way we code and present web content. In the first Top HTML5 Features article, we reviewed the original goals of the HTML5 specification as well as some of its most successful and notable improvements: the DOCTYPE, FIGURE, and INPUT fields. In today’s follow-up, we’ve got a few more great additions to the HTML spec, including simplified script and link tags, the autofocus feature, and more.

No More Type Attribute for Script and Link Tags

As of HTML5, the type attribute is no longer necessary for script and link tags. It’s implied that both of these tags refer to scripts and stylesheets, respectively.

<link type="text/css" rel="stylesheet" href="path/to/stylesheet.css" />
<script type="text/javascript" src="path/to/script.js"></script>

So, in the words of the Donald, if you’re still including the type attribute to your link and script tags, just “stop it!”

<link rel="stylesheet" href="path/to/stylesheet.css" />
<script src="path/to/script.js"></script>

The Form Field Autofocus Attribute

This Boolean attribute lets you specify that a form field should have input focus when the page loads, unless the user overrides it, for example, by typing in a different field. Only one form element in a document can have the autofocus attribute.

<form>
  First name: <input type="text" name="fname" autofocus><br/>
  Last name:  <input type="text" name="lname"><br/>
  <button value="submit" />
</form>

Here is the result, presented in its own iFrame, so as to not be affected by the parent page source:

Custom Data Attributes (data-*)

Prior to HTML5, including your own custom attributes in a tag came with some very real risks. Although it would not stop the page from rendering, it could make the document “invalid”, thus telling the browser to render it in quirksmode. Thanks to the new data-* attribute, that’s all in the past now.

Using the data-* attribute to include custom data in the page or application gives developers the ability to create a more engaging user experience without any Ajax calls or server-side lookups by referencing the data-* attributes via JavaScript.

How you use the data-* attribute is completely up to you, but the idea is to store extra information about the element. The data can be stored as a simple string to composite structures like arrays or JSON objects, provided that the object can be serialized.

<div id="storageElement" data-storeHelloWorld='[{"a":"hello"},{"a":"world"}]'></div>

JavaScript supports the [get/set]Attribute() methods for accessing data-* attribute values. It’s an instance method of the DOMElement type so you can invoke it directly on the element using dot (element.) notation:

//reference the element
var storageElement = document.getElementById('storageElement');
//read the data-* attribute
var storedData     = storageElement.getAttribute('data-storeHelloWorld');
//convert the string back into an object
var jsonArray      = JSON.parse( storedData );

JS libraries like jQuery have their own methods for working with data-* attribute values. Here’s jQuery’s data() method, which does not require the “data-” prefix:

var jsonArray = JSON.parse( $("storageElement").data("storeHelloWorld") );

Local Storage

One of the most limiting factors in the evolution of web content from pages to applications is the stateless nature of HTTP. This means that when you visit a page or application and then close the tab or browser, that page or application’s state will be reset the next time you open it. In the past, developers who needed to store some state information had very few choices: either store it on the server or in cookies. Neither of these choices were particularly satisfactory; server-side data needed to be associated with the client (session), and cookies were limited to about 4KB. Not to mention, these could be turned off by the user.

Local storage makes saving state data on the user’s device a snap. The localStorage object is part of the global window namespace so it’s accessible from anywhere within your scripts:

localStorage.setItem('favoriteflavor','chocolate');

//If you read out the favoriteflavor key, you will get back "chocolate":
var taste = localStorage.getItem('favoriteflavor');  // "chocolate"

//To remove the item, you can use the removeItem() method:
localStorage.removeItem('favoriteflavor');
var taste = localStorage.getItem('favoriteflavor');  // -> null

Like the data-* attribute, local storage can only store string values. Therefore, in order to store an object, you have to serialize it into string form. That’s where the native JSON.stringify() and JSON.parse() methods can be of tremendous value:

var car = {};
car.wheels = 4;
car.doors = 2;
car.sound = 'vroom, vroom!';
car.name = 'Infiniti Q50';

localStorage.setItem( 'car', JSON.stringify(car) );

//later...
var storedCar = JSON.parse( localStorage.getItem('car') );

local_storage_in_chrome_debugger.jpg

By the way, you can use sessionStorage instead of localStorage if you want the data to be maintained only until the browser window closes. You can see it in the screenshot above as well.

Native Audio and Video Support

HTML5 now supports audio and video natively via the audio and video elements.

Supported file formats include ogg, wav, and mp3.

<audio autoplay="autoplay" controls="controls">
    <source src="audio_file.ogg" />
    <source src="audio_file.mp3" />
    <a>Download this file.</a>
</audio>

Supported video types aren’t as clear-cut as audio, but the following all enjoy some level of support:

  • WebM
  • Ogg Theora Vorbis
  • Ogg Opus
  • Ogg FLAC
  • MP4 H.264 (AAC or MP3)
  • MP4 FLAC
  • MP3
  • WAVE PCM
  • FLAC
<video controls preload>
    <source src="video_file.ogv" type="video/ogg; codecs='vorbis, theora'" />
    <source src="video_file.mp4" type="video/mp4; 'codecs='avc1.42E01E, mp4a.40.2'" />
    <p> Your browser does not support the video element. <a href="video_file.mp4">Download this video instead.</a> </p>
    <!-- You can embed a Flash player here, to play your mp4 video in older browsers -->
</video>

Conclusion

HTML5 was a huge leap forward from the 4.1 spec, rendering cumbersome workarounds using browser extensions, plugins, shims, JavaScript code and server-side technologies obsolete in favor of native support.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured