DEV Community

Cover image for Introducing jquery-events-to-dom-events (and jboo)
leastbad
leastbad

Posted on

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.

Top comments (2)

Collapse
 
adrienpoly profile image
Adrien Poly

Nice, this would have been helpful in some older projects. I am trying to run away from jQuery and this looks like a nice solution when there is no choice (BS4 as an example).

Collapse
 
leastbad profile image
leastbad

One thing I recently figured out is that if you're running Bootstrap's master branch, you're essentially running Bootstrap 5. BS5 checks for the presence of jQuery, and if it finds it, you'll get jQuery events. If there's no jQuery present, it'll emit DOM events.

I'm thrilled, now that I know. But man, this would have saved a lot of time.

For what it's worth, BS5 has been almost perfectly drop-in compatible with BS4 so far as I can tell.