Triggering custom events in jQuery

jQuery is brilliant - and you seem to learn something new and cool about it every day.

Today's cool new thing was being able to trigger (and respond to) custom event types.

Here's an example...

I have a JavaScript function that opens an overlay window.

I later realised when re-using this function on another page, that some extra actions were required when the overlay opens and closes (in this particular case, to pause a Flowplayer video when the overlay opens, and then start it playing again when the overlay closes).

This had me scratching my head for a bit, but then after a bit of Googling, I discovered that in the function that opens the overlay, I can just add this one line of code at an appropriate stage:

$("#my-element").trigger("overlayOpened");

Or, perhaps something like $(this).trigger("overlayOpened"); - if your code is structured in that way.

To respond to this custom event, I then just needed to write a standard jQuery event handler:

$(document).on("overlayOpened", "#my-element", function()
{
   // .. code to do stuff when the overlay opens
});

It's as simple as that.

Comments