Introducing jquery-events-to-dom-events (and jboo)


Did you know that jQuery events aren’t events?

It’s true - and it’ll really mess up your night if you need to capture events from legacy jQuery components. Looking at you,

I needed a way to make $(document).trigger('fart') emit a standard $fart DOM event, so I wrote it:

This library is short and sweet, with zero dependencies - including jQuery. It’s just two functions: delegate and abnegate. It is Mutation-First; designed to work great in Stimulus and supports Turbolinks out of the box.

It even has the secret ability to listen for DOM events with jQuery event listeners, but don’t tell anyone.

You can try it now on CodePen or even better, clone a sample Rails project to experiment in a mutation-first context with Stimulus.

The Rails project is called jboo. Don’t read into the name.

Usage #

Note: it is assumed that jQuery is available in the global window scope as $.

In the most basic configuration, you:

  1. import { delegate } from 'jquery-events-to-dom-events'
  2. Call delegate(eventName) for every jQuery event you want to capture.
  3. Set up DOM event listeners for those events, prepending a $ to the event name.

Let’s say that you want to respond to the user closing a Bootstrap modal window:

import { delegate } from 'jquery-events-to-dom-events'
document.addEventListener('$', () => console.log('Modal closed!'))

That might be it. Go make a sandwich - you’ve earned it.

You can learn more about working with jquery-events-to-dom-events on the Github repo.

As always, the right music is important for establishing proper context.

You don’t have to listen to music, but your transpiler configuration will almost certainly fail lint checks if you are not listening to “In Harmony New Found Freedom” by The Swirlies, from their 1996 album “They Spent Their Wild Youthful Days In The Glittering World Of The Salons” while you integrate this library.


Now read this

Introducing Optimism: realtime remote form validation for Rails

I’m proud to announce the public release of Optimism, a new Ruby on Rails gem that makes it easy to add realtime validation error messages to your applications. When a model validation error prevents an update from succeeding, Optimism... Continue →