5 HTML5 APIs You Didn’t Know Existed

Written by David Walsh on September 27, 2012 · 28 Comments

When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature addition like placeholder made us "take a minute."  Despite many HTML5 features being implemented in modern browsers, many developers are unaware of some of the smaller, useful APIs available to us.  This post exposes those APIs and was written to encourage you to explore the lessor known HTML5 APIs!

Element.classList

The classList API provides the basic CSS controls our JavaScript libraries have been giving us for years:

// Add a class to an element
myElement.classList.add("newClass");

// Remove a class to an element
myElement.classList.remove("existingClass");

// Check for existence
myElement.classList.contains("oneClass");

// Toggle a class
myElement.classList.toggle("anotherClass");

The epitome of a great API addition: simple and intelligent. Read this post to learn about a few other classList properties.

ContextMenu API

The new ContextMenu API is excellent:  instead of overriding the browser context menu, the new ContextMenu API allows you to simply add items to the browser's context menu:

<section contextmenu="mymenu">
  <!-- 
    For the purpose of cleanliness, 
    I'll put my menu inside the element that will use it 
  -->

  <!-- add the menu -->
  <menu type="context" id="mymenu">
	  <menuitem label="Refresh Post" onclick="window.location.reload();" icon="/images/refresh-icon.png"></menuitem>
	  <menu label="Share on..." icon="/images/share_icon.gif">
	    <menuitem label="Twitter" icon="/images/twitter_icon.gif" onclick="goTo('//twitter.com/intent/tweet?text=' + document.title + ':  ' + window.location.href);"></menuitem>
	    <menuitem label="Facebook" icon="/images/facebook_icon16x16.gif" onclick="goTo('//facebook.com/sharer/sharer.php?u=' + window.location.href);"></menuitem>
	  </menu>
	</menu>
</section>

Note that it's best to create your menu markup with JavaScript since JS is required to make item actions work, and you wouldn't want the HTML in the page if JS is turned off.

Element.dataset

The dataset API allows developers to get and set data- attribute values:

/*  Assuming element:

	<div id="myDiv" data-name="myDiv" data-id="myId" data-my-custom-key="This is the value"></div>

*/

// Get the element
var element = document.getElementById("myDiv");

// Get the id
var id = element.dataset.id;

// Retrieves "data-my-custom-key"
var customKey = element.dataset.myCustomKey;

// Sets the value to something else
element.dataset.myCustomKey = "Some other value";

	// Element becomes:
	//    <div id="myDiv" data-name="myDiv" data-id="myId" data-my-custom-key="Some other value"></div>  

Not much more to say; just like classList, simple and effective.

window.postMessage API

The postMessage API, which has even been supported in IE8 for years, allows for message sending between windows and IFRAME elements:

// From window or frame on domain 1, send a message to the iframe which hosts another domain
var iframeWindow = document.getElementById("iframe").contentWindow;
iframeWindow.postMessage("Hello from the first window!");

// From inside the iframe on different host, receive message
window.addEventListener("message", function(event) {
	// Make sure we trust the sending domain
	if(event.origin == "http://davidwalsh.name") {
		// Log out the message
		console.log(event.data);

		// Send a message back
		event.source.postMessage("Hello back!");
	}
]);

Messages may only be strings, but you could always use JSON.stringify and JSON.parse for more meaningful data!

autofocus Attribute

The autofocus attribute ensures that a given BUTTON, INPUT, or TEXTAREA element is focused on when the page is ready:

<input autofocus="autofocus" />
<button autofocus="autofocus">Hi!</button>
<textarea autofocus="autofocus"></textarea>

Admittedly the autofocus attribute is disorienting for the visually impaired, but on simple search pages, it's the perfect addition.

Browser support for each API differs, so use feature detection before using each API.  Take a few moments to read the detailed posts on each feature above -- you'll learn a lot and hopefully get a chance to tinker with each API!

Comments

  1. I knew about all of these.

  2. Didn’t know about the ContextMenuAPI thanks again for a useful post David

  3. The contextmenu seems like a good idea (at least vs. the IE hacks) however according to http://caniuse.com/#search=contextmenu it is only expected in Firefox… and not for another 2 versions… thus I suspect full browser support to be several years away.

  4. Would be nice if you list what browsers supports each API as well.

  5. Apparently my browser does not know these APIs exist either!

  6. There is a reason some of these are lesser-known.

  7. I would love if the context menu API was fully customizable via css, something tells me that if such feature would ever come to existence, chrome would have implement it first (just like the scrollbars).

  8. Sky Lamer September 28, 2012

    I knew it all man… so stop lying!

  9. Great post, knew all except the context menu API which I’m sure will come in handy for a project I’m working on using the chromium embedded framework.

    Thanks.

    David

  10. “you wouldn’t want the HTML in the page if JS is turned off”

    I’m not contesting your thought, but I wonder: then why is it HTML? Wouldn’t a javascript API be better suited?

  11. Well, those are obviously lesser-known since it is not supported by major browsers…

  12. Mircea Piturca October 1, 2012

    @RONILDO COSTA
    “Would be nice if you list what browsers supports each API as well.” – just type “window” in your browser console and you will see what is supported. Nice way to find new, and old, cool stuff also

  13. … and you still have to use jQuery (or else) because of MSIE.
    *sigh* frustrating

  14. bakaohki October 3, 2012

    Autofocusing on search fields is pretty annoying imo: I can not scroll the page with the keyboard and most of the time it takes a couple of seconds to realize it and then grab the mouse and click out.

  15. True. I agree with Bakaohki!

  16. Per the Context Menu example, wouldn’t the HTML be hidden anyway? If a browser doesn’t support menu/menuitem, then those items will be hidden from display. It seems to me this is safe to use anywhere.

  17. Hey good stuff, I wasn’t aware of some of these.

  18. These are all very solid, I’m most excited about the ContextMenu API. Could be used for some very cool things especially regarding social media and what not.

  19. I think the HTML5 API with the highest potential : fame ratio is .

    Shameless self promotion, but:

    http://www.html5rocks.com/en/tutorials/track/basics/

  20. I think the HTML5 API with the highest potential : fame ratio is the track elment.

    Shameless self promotion, but: <www.html5rocks.com/en/tutorials/track/basics/

    (Shouldn't have used angle brackets in first comment :^/.)

  21. Really awesome tips, I knew the autofocus and the postMessage one, really awesome that they’ve added classList and dataset.

  22. Where are the news? ;-) And again: studying closely Firefox release notes on regular basis has some advantages.

  23. does this work on smartphones?

  24. Awesome tutorial,
    @Darren HTML5 can work on smartphones :)

  25. Go to w3fools.com. w3schools doesn’t know what it’s doing.

Be Heard

Tip: Wrap your code in <pre> tags or link to a GitHub Gist!

Use Code Editor
Older
Who I Use: Hosting & Domain
Newer
Confessions of a Web Developer XII