Drupal 8 JS event after opening AJAX modal

Posted on 27/10/2020

Drupal provides a few custom events for AJAX modals. Even though the modal itself is provided by jQuery UI library, these events are custom and are provided by Drupal itself.

There are a few events you can use here:

  • dialog:beforecreate
  • dialog:aftercreate
  • dialog:beforeclose
  • dialog:afterclose

All of them are triggered on the window. Below is sample code that can be used in a custom theme or custom module:

  1. (function ($, Drupal) {
  2.   Drupal.behaviors.sampleModalReaction = {
  3.     attach: function(context) {
  4.       $(window)
  5.         .once()
  6.         .on('dialog:aftercreate', function(dialog, $element, settings) {
  7.           console.log('modal is opened!');
  8.         });
  9.     }
  10.   };
  11. })(jQuery, Drupal);

You can read the source code in /core/misc/dialog/dialog.js file to understand how everything works.