title: Progressive enhancement with handlers and enhancers
url: https://hiddedevries.nl/en/blog/2015-04-03-progressive-enhancement-with-handlers-and-enhancers
hash_url: ba6ef65c13ffa3b92e95fb486cfc6fe0

<p class="intro">Recently I adopted a different way to manage bits of JavaScript in websites I was building. It exercises progressive enhancement (PE) by declaring handler and enhancer functions on <span class="caps">HTML</span> elements.</p>

<p><strong>TL;DR</strong>: When JavaScript is used to handle user interactions like clicks, or enhance the page by manipulating the <span class="caps">DOM</span>, traditionally you&#8217;d have JavaScript find that <span class="caps">HTML</span> element in your page, and hook some code into it. But what if you&#8217;d switch that around, and have the <span class="caps">HTML</span> element “tell” JavaScript what function to execute?</p>

<p>How? I declare JavaScript functions on <span class="caps">HTML</span> elements. Separating them to functions that happen on click and those that happen on page load, I use two attributes (<code>data-handler</code> and <code>data-enhancer</code>) that both get space-separated function names as their values. Then, with a little bit of JavaScript, I make sure the functions execute when they need to.</p>

<p>Note that this works best for websites for which the mark-up is rendered on the server, to which JavaScript is added as an extra layer. Websites that rely on JavaScript for rendering content will probably have options to do the same within the framework they are built with.</p>

<h2>Separating to handlers and enhancers</h2>

<p>On many small to medium sized websites, the required JavaScript can be drilled down to two types of usage: </p>

<ol>
    <li>things that need to happen on a click</li>
    <li>enhancements after the inital page load</li>
</ol>

<p>Surely, there are often other events we want to use for triggering JavaScript (scroll, anyone?), but let&#8217;s focus on these two types first.</p>

<p>Many simple websites will have both types of script in a single <code>scripts.js</code> file, which is also used to query the nodes interactions need to happen on, and to add click handlers to those nodes.</p>

<p>This year, <a href="http://krijnhoetmer.nl">Krijn</a> and <a href="http://brinkhu.is">Matijs</a> introduced me to a new way to go about this. It has proven to be a very powerful pattern in some of my recent projects, which is why I’d like to share it here. Credits for the pattern, and for the initialisation functions I will discuss later, go to them.</p>

<h2>Including JavaScript functions to the declarative model</h2>

<p>The pattern starts from the idea that web pages have three layers to them: structure (<span class="caps">HTML</span>), lay-out (<span class="caps">CSS</span>) and enhancement (JavaScript). <span class="caps">HTML</span> is a declarative language: as an author, you declare what you’d like something to be, and that is what it will be. </p>

<blockquote class="in-content">
    <p class="in-content">Let this be a header, let this be a list item, let this be a block quote.</p>
</blockquote>

<p>This is great, browsers can now know that ‘this’ is a list item, and treat it as such. Screenreaders may announce it as a list, your <span class="caps">RSS</span> reader or mobile Safari “reader view” can view it as a list, et cetera.</p>

<p>With <span class="caps">CSS</span> we declare what things look like:</p>

<blockquote class="in-content">
    <p class="in-content">Let headers be dark blue, let list items have blue bullets and let block quotes render in slightly smaller type.</p>
</blockquote>

<p>This works rather well for us, because now we don’t need to think about what will happen if we add another list item. It being a list item, it will have the <span class="caps">CSS</span> applied to it, so it will have blue bullets.  </p>

<p>The idea I’d like to share here, is that of making JavaScript functions part of this declarative model. If we can declare what something looks like in <span class="caps">HTML</span>, why not declare what its behaviour is, too?</p>


<h2 id="handlers">Handlers: things that happen on a click</h2>

<p>The idea is simple: we introduce a <code>data-handler</code> attribute to all elements that need to trigger function execution. As their value, we add one or more functions name(s) that need(s) to execute on click. </p>

<p>For example, here’s a link:</p>

<pre class="language-markup"><code>&lt;a href=&quot;#punk-ipa&quot;&gt;More about Punk IPA&lt;/a&gt;</code></pre>

<p>This is an in-page link to a section that explains more about Punk <span class="caps">IPA</span>. It will work regardless of JavaScript, but can be improved with it.</p>

<p>Cooler than linking to a section about Punk <span class="caps">IPA</span>, is to have some sort of overlay open, with or without a fancy animation. We add a <code>data-handler</code> attribute:</p>

<pre class="language-markup"><code>&lt;a href=&quot;#punk-ipa&quot; data-handler=&quot;overlay&quot;&gt;More about Punk IPA&lt;/a&gt; </code></pre>

<p>In the data-handler, the value holds a function name, in this case ‘overlay’. The idea is that the overlay function executes when the link is clicked. Naturally, you would be able to add more than one function name, and separate function names by spaces. This works just like <code>class=&quot;foo bar&quot;</code>.</p>

<p>Within the function declaration, we will know which element was clicked, so we can access attributes. We can access the <code>href</code> or any data attribute. With that, it can grab the content that’s being linked to, append it into some sort of overlay, and smoothly transition the overlay into the page.</p>

<p>Note that this is similar to doing <code>&lt;a onclick=&quot;overlayfunction(); anotherfunction();&quot;&gt;</code>, but with the added benefit that a <code>data-handler</code> only gets meaning once JavaScript is active and running, and that it contains strings like <span class="caps">CSS</span> classes, instead of actual JavaScript code. This way, the scripting is separated in the same way as the style rules are.</p>

<p>Also note that is best practice to only add handlers to <span class="caps">HTML</span> elements that are made for click behaviour, like <code>&lt;button&gt;</code>s and <code>&lt;a&gt;</code>.</p>

<h3>Adding function definitions</h3>

<p>In our JavaScript (e.g. an included <code>scripts.js</code> file), we add all functions for click behaviour to one object: </p>

<pre class="language-javascript"><code>var handlers = {
    &#039;function-name&#039; : function(e) {
         // This function is executed on click of any element with 
         // &#039;function-name&#039; in its data-handler attribute.
         // The click event is in &#039;e&#039;, $(this).attr(&#039;data-foo&#039;) holds the
         // value of data-foo of the element the user clicked on 
    },
    &#039;another-function-name&#039; : function(e) {}
};</code></pre>

<p>Those working in teams could consider making the handler object global. That way functions can have their own files, making collaboration through version control easier.</p>

<h3>Adding click handling: one handler to rule them all</h3>

<p>If we set all our click-requiring functionality up within <code>data-handler</code> attributes, we only need to attach one click handler to our document. <a href="http://davidwalsh.name/event-delegate">Event delegation</a> can then be used to do stuff to the actual element that is clicked on, even when that actual element did not exist on page load (i.e. was loaded in with <span class="caps">AJAX</span>).</p>

<p>This function (jQuery) can be used to handle clicks, then search through the handler functions and apply the ones specified in the data-handler function:</p>

<pre class="language-javascript"><code>$(function() {
    &#039;use strict&#039;;
    // generic click handler
    $(document).on(&#039;click&#039;, &#039;[data-handler]&#039;, function(event) {
        var handler = this.getAttribute(&#039;data-handler&#039;);
        // 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 === &#039;A&#039; &amp;&amp; (event.metaKey || event.ctrlKey || event.shiftKey)) {
            return;
        }
        if (handlers &amp;&amp; typeof handlers[handler] === &#039;function&#039;) {
            handlers[handler].call(this, event);
        }
        else {
            if (window.console &amp;&amp; typeof console.log === &#039;function&#039;) {
                console.log(&#039;Non-existing handler: &quot;%s&quot; on %o&#039;, handler, this);
            }
        }
    });
});</code></pre>

<p>(<a href="https://gist.github.com/matijs/5b2d6675265ec440bcba">Source</a>; see also <a href="https://gist.github.com/matijs/9bb314a9a184b53952e2">its vanilla JavaScript version</a>)</p>

<h2 id="enhancers">Enhancers: things that happen after page load</h2>

<p>We can run functions to enhance elements in a similar way, by adding their function names to a <code>data-enhancer</code> attribute. The corresponding functions go into a <code>enhancers</code> object, just like the <code>handlers</code> object above.</p>

<p>For example, a page element that needs to display tweets. Again, here&#8217;s a link:</p>

<pre class="language-markup"><code>&lt;a href=&quot;https://twitter.com/bbc&quot;&gt;Tweets of the BBC&lt;/a&gt;</code></pre>

<p>To enhance this link to the <span class="caps">BBC</span>&#8217;s tweets, we may want to load a widget that displays actual tweets. The function to do that may add some container <code>&lt;div&gt;</code>s, and run some calls to the Twitter <span class="caps">API</span> to grab tweets. To trigger this function:</p>

<pre class="language-markup"><code>&lt;a href=&quot;https://twitter.com/bbc&quot; data-enhancer=&quot;twitter-widget&quot;&gt;
Tweets of the BBC&lt;/a&gt;</code></pre>

<p>To find out whose Twitter widget to display, our function could analyse the <span class="caps">URL</span> in the <code>href</code> attribute, or we can add an extra attribute:</p>

<pre class="language-markup"><code>&lt;a href=&quot;https://twitter.com/bbc&quot; data-enhancer=&quot;twitter-widget&quot; 
data-twitter-user=&quot;bbc&quot;&gt;Tweets of the BBC&lt;/a&gt;</code></pre>

<p>Another example: of a large amount of text, we want to hide all but the first paragraph, then add a “Show all” button to show the remainder. The <span class="caps">HTML</span> will contain all of the content, and we will hide the remainder with JavaScript.</p>

<pre class="language-markup"><code>&lt;section&gt;
    &lt;p&gt;Some text&lt;/p&gt;
    &lt;p&gt;Some more text&lt;/p&gt;
    &lt;p&gt;Some more text&lt;/p&gt;
&lt;/section&gt;</code></pre>

<p>To the block of text we add a data-enhancer function that makes sure everything but the first paragraph is hidden, and a “Show all” button is added.</p>

<pre class="language-markup"><code>&lt;section data-enhancer=&quot;only-show-first-paragraph&quot;&gt;
    &lt;p&gt;Some text&lt;/p&gt;
    &lt;p&gt;Some more text&lt;/p&gt;
    &lt;p&gt;Some more text&lt;/p&gt;
&lt;/section&gt;</code></pre>

<p>A function named ‘only-show-first-paragraph’ could then take care of removing the content, and adding a button that reveals it (this button could have a <code>data-handler</code> for that behaviour).</p>

<h3>Running all enhancements</h3>

<p>Assuming all our <code>enhancer</code> functions are in one <code>enhancer</code> object, we can run all <code>enhancers</code> on a page with one function. The function looks for all elements with a <code>data-enhancer</code> attribute, and calls the appropriate functions.</p>

<pre class="language-javascript"><code>$(function() {
    &#039;use strict&#039;;
    // kick off js enhancements
    $(&#039;[data-enhancer]&#039;).each(function() {
        var enhancer = this.getAttribute(&#039;data-enhancer&#039;);
        if (enhancers &amp;&amp; typeof enhancers[enhancer] === &#039;function&#039;) {
            enhancers[enhancer].call(this);
        }
        else {
            if (window.console &amp;&amp; typeof console.log === &#039;function&#039;) {
                console.log(&#039;Non-existing enhancer: &quot;%s&quot; on %o&#039;, enhancer, this);
            }
        }
    });
});</code></pre>

<h2>Wrap-up</h2>

<p>So the basic idea is: functions for click behaviour are handlers, and those that happen on page load are enhancers. They are stored in a <code>handlers</code> and <code>enhancers</code> object respectively, and triggered from <span class="caps">HTML</span> elements that have <code>data-handler</code> and <code>data-enhancer</code> attributes on them, to declare which functions they need.</p>

<p>In summary: </p>

<ol>
    <li>All functions that need to execute on click (or touch or pointer events), are declared on the <span class="caps">HTML</span> element that should trigger the click, in a <code>data-handler</code> attribute</li>
    <li>All functions that need to change/enhance stuff on the <span class="caps">DOM</span>, are declared on the <span class="caps">HTML</span> element they need to change, in a <code>data-enhancer</code> attribute</li>
    <li>Two JavaScript functions run through <code>data-handler</code> and <code>data-enhancer</code> attributes respectively, and execute all functions when they are required</li>
</ol>

<h2>Thoughts?</h2>

<p>This pattern is not new, similar things have been done by others. Rik Schennink wrote about <a href="http://rikschennink.nl/thoughts/controlling-behaviour/">controlling behaviour</a> before, and his <a href="http://conditionerjs.com">conditioner.js</a> deserves special mention. It is a library that not only manages modules of JavaScript, it also activates them based on responsive breakpoints, something the pattern described here does not do out of the box (it could).</p>

<p>For me and teams I worked in, the above has proven to be a useful way to declare actions and enhancements within pages. It adds maintainability, because it helps keeping functions organised. It also promotes reusability: although new functions can be added for each use, multiple elements can make use of the same function. </p>

<p>The method is not perfect for every project, and it can definitely be improved upon. For example, we could add the function that triggers all <code>data-handler</code> functions to an enhancer (<code>&lt;html data-enhancer=&quot;add-handlers&quot;&gt;</code>), as it is an enhancement (of the page) by itself. In big projects with many people working on the same codebase, it may be useful to have all functions in separate files and have a globally available handlers object.</p>

<p><em>Update 07/04/2015</em>: I have opened comments, would love to hear any feedback</p>
