Frontend recipes Onmount behaviors

When injecting JavaScript into pages, prefer to use React custom elements whenever possible. For cases when this approach may not be feasible, consider trying RSJS-style behaviors using onmount.

About RSJS

The RSJS guidelines outlines some rules on sorting your JavaScript for non-SPA applications.

  • Think of DOM pieces as "components," much as you would with RSCSS or React.
  • Think of your JavaScript as "behaviors" that you attach to components.
  • Label your behavior targets with data-js-* attributes.

Example

In this example, we'll attach a data-js-hint-text attribute to a DOM element in our markup.

<span class="sample-text" data-js-hint-text="This is awesome">Hover on me</span>

We can then define the behavior to be attached to this component using Onmount. Here's an example behavior that will bind a DOM event to invoke a custom 3rd-party tooltip plugin:

import onmount from 'onmount'

onmount('[data-js-hint-text]', function() {
  const el = this
  const text = this.dataset.jsHintText

  this.addEventListener('mouseover', e => {
    e.preventDefault()
    CustomTooltip.show(el, text)
  })
})

Anti-patterns

There are some common coding patterns forbidden in the RSJS guidelines. As such, we tend to discourage these patterns. Some of these anti-patterns include:

  • Don't attach behaviors to CSS classes. Leave CSS classes to presentations. RSJS describes why you shouldn't overload CSS class names.

  • When attaching a behavior to a component, don't modify elements outside that component. Each behavior is an encapsulated piece of functionality that should be indepenent of other factors as much as possible.

Notes

  • Consider using React custom elements whenever possible. While it may be more work to set up sometimes, it will make it easier to eventually add new functionality with it.

  • Use [data-js-xxxxx] instead of [role~="xxxxx"]. The use of the role attribute was deprecated in rsjs since it can potentially interfere with screen readers.

  • Avoid using jQuery, and favor using regular DOM API's.

  • Behaviors made with onmount can be tested, so create unit tests for it!

See also

  • onmount - Run functions when an element is mounted
  • rsjs - Reasonable Structure for JavaScript