DOM Hooks

Smarter ways to target elements in the DOM.

The problem

One hook to do all the things e.g.

<button class="btn-menu">

The .btn-menu class could be used as a hook for:

  • CSS styles
  • JavaScript behaviours
  • Automated tests
  • Tracking e.g. Google Analytics
Fragile Handle with care

The solution

A naming convention that enforces a clear separation of concerns e.g.

<button class="[css]  [js]  [test]  [track]">

This means there will never be any troublesome overlap.

Solid

Meet the hooks

All hooks are namespaced except for CSS hooks:

  • .js- = JavaScript hook
  • .test- = Automated test hook
  • .track- = Tracking hook
<button class="drop-down-btn btn-menu  js-header-menu-btn  test-header-menu-btn  track-header-menu-btn">

CSS hooks don't have a namespace but in the scope of the Scally framework some CSS hooks do e.g. .l- (a layout module) and .u- (a utility). Plus any state based hooks are namespaced with .is- e.g. .is-active, .is-hidden.

Order of the hooks

The order of the hooks, within the class attribute, should be:

  1. Style hooks:
    1. Component hook (no namespace)
    2. Layout hook (.l-)
    3. Utility hook (.u-)
  2. JavaScript hooks (.js-)
  3. Test hooks (.test-)
  4. Tracking hooks (.track-)
GitHub commit comment GitHub commit converstation between Chris Pearce and Ian Tinsley
GitHub commit comment

A common practice is to use HTML5 data-* attributes as hooks, but this is incorrect. data-* attributes, as per the spec, are used to store custom data private to the page or application. data-* attributes are designed to store data, not be bound to.

Thank you

Read more in my CSS Guidelines.

http://presentation.chris-pearce.me/DOM-hooks