Progressive enhancement with handlers and enhancers

var handlers = {
	'overlay' : function(e) {
		 // This function is executed on click of any element with 
		 // 'overlay' in its data-handler attribute.
		 // The click event is in 'e', $(this).attr('data-foo') holds the
		 // value of data-foo of the element the user clicked on 
    'another-function-name' : function(e) {}

$(function() {
    'use strict';
    // generic click handler
    $(document).on('click', '[data-handler]', function(event) {
        var handler = this.getAttribute('data-handler');
        // honour default behaviour when using modifier keys when clicking
        // for example:
        // cmd + click / ctrl + click opens a link in a new tab
        // shift + click opens a link in a new window
        if (this.tagName === 'A' && (event.metaKey || event.ctrlKey || event.shiftKey)) {
        if (handlers && typeof handlers[handler] === 'function') {
            handlers[handler].call(this, event);
        else {
            if (window.console && typeof console.log === 'function') {
                console.log('Non-existing handler: "%s" on %o', handler, this);

Hidde De Vries (@hdv):

When JavaScript is used to handle user interactions like clicks, or enhance the page by manipulating the DOM, traditionally you’d have JavaScript find that HTML element in your page, and hook some code into it. But what if you’d switch that around, and have the HTML element “tell” JavaScript what function to execute?

Using a tad of JavaScript the link below will be opened in an overlay upon click, instead of the normal flow:

<a href="#punk-ipa" data-handler="overlay">More about Punk IPA</a>

Reminds me of the data-showinoverlay attribute I add to links which need to be shown in an overlay. Great to see that Hidde took a generic approach to this as my data-showinoverlay approach is limited to only that one functionality.

Next to handlers, enhancers are also discussed.

Progressive enhancement with handlers and enhancers →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.