O'Reilly

5 HTML5 APIs You Didn’t Know Existed

By on  

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!

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

  • Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • Image Reflections with CSS

    Image reflection is a great way to subtly spice up an image.  The first method of creating these reflections was baking them right into the images themselves.  Within the past few years, we've introduced JavaScript strategies and CANVAS alternatives to achieve image reflections without...

  • jQuery Link Nudging

    A few weeks back I wrote an article about MooTools Link Nudging, which is essentially a classy, subtle link animation achieved by adding left padding on mouseover and removing it on mouseout. Here's how to do it using jQuery: The jQuery JavaScript It's important to keep...

Discussion

  1. Mystic

    I knew about all of these.

    • Wiwa

      I did too ¬¬_

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

  3. Steve

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

    Apparently my browser does not know these APIs exist either!

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

  7. Alex

    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

    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

    @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. Drop

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

  14. bakaohki

    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.

    • I think this would be useful on mobile applications

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

    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.

  26. Adrian

    I don’t get the reason for the data-set api,
    I tack my own attributes on elements all the time,
    and call them whatever I want.

    fu=document.getElementById('masthead-title')
    
    div aria-hidden="true" id="masthead-title">
    
    
    fu.setAttribute("splat",5)
    undefined
    fu
    
    fu.splat
    "5"
    

    Am I missing something?

  27. Steve

    @Adrian you’re correct that you can use any attribute you want but you run the risk of a future HTML version claiming that attribute. E.g if you added a parent attribute HTML6 could come along and use that to do something else. You’d be well advised to stick with data-... attributes that the spec has provided for you to do your own custom thing with. E.g you’re future proofing your code.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Preventing Side Effects in JavaScript

    JavaScript is very dynamic these days but I still see a lot of legacy code, whether it be for optimal backward compatibility or simply that the code hasn't been maintained.  One of the practices that makes me cringe is coding that creates unwanted side effects.  What's a side...

  • Access Mac Camera by Command Line

    With all of my recent command line tutorials, I've really gotten excited about the shell's simplicity and realized the true power of using the underlying technology of pretty UIs.  Since I work from home, I spend a lot of time on video calls, so when...

  • Open Files from Command Line on OS X

    I'm as much of a fan of application UIs as anyone else but I'm finding myself working more and more from the command line lately.  Much of that is becoming obsessed with media manipulation but I'm forcing myself to use less UIs so that I...

  • Get Stock Quotes From Command Line

    When I conned my way into my first professional programming gig, I didn't really think much about money -- just that I was getting my foot in the door.  But as my career has gone on, I've been more aware of money, investing, and retirement.  I've recently...

  • Geolocation API

    One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...