Read more

Unobtrusive JavaScript helper to progressively enhance HTML

Henning Koch
August 25, 2021Software engineer at makandra GmbH

The attached compiler() function below applies JavaScript behavior to matching HTML elements as they enter the DOM.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

This works like an Unpoly compiler Show archive.org snapshot for apps that don't use Unpoly Show archive.org snapshot , Custom Elements Show archive.org snapshot or any other mechanism that pairs JavaScript with HTML elements.

The compiler() function is also a lightweight replacement for our legacy $.unobtrusive() helper (no jQuery required).

Basic usage

Compilers are registered with a CSS selector and a callback function. The function is called with each new element that matches the selector.

The following compiler will remove flash messages (<div class="flash">) after 5 seconds, or when clicked:

compiler('.flash', (element) => {
  let removeFlash = () => element.remove()
  element.addEventListener('click', removeFlash)
  setTimeout(removeFlash, 5000)
})

Compilers are also a great tool to initialize JavaScript libraries. For example, the following will initialize Tom Select Show archive.org snapshot on all <select> elements:

compiler('select', (element) => {
  new TomSelect(element, { searchEnabled: true })
})

Elements are compiled automatically

Matching elements will always be compiled automatically, regardless of when and how the element entered the DOM. There is no function to manually compile a new element.

The initial page is compiled once the DOM is parsed (DOMContentLoaded event).

When matching elements enter the DOM after the initial page load, they are also compiled automatically. You do not need to manually activate elements that were added dynamically by JavaScript.

Cleaning up

To prevent memory leaks you sometimes need to run code when an element is removed from the DOM.

When your compiler returns a function, it is called when the element is detached from the DOM:

compiler('textarea.wysiwyg', (select) => {
  let editor = new SuperEditor(select) 
  return () => editor.shutdown()
})
Posted by Henning Koch to makandra dev (2021-08-25 14:40)