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

leastbad

leastbad

Posted on May 12, 2020

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, hidden.bs.modal.

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

https://www.npmjs.com/package/jquery-events-to-dom-events

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'
delegate('hidden.bs.modal')
document.addEventListener('$hidden.bs.modal', () => 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.

💖 💪 🙅 🚩
leastbad
leastbad

Posted on May 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related