1

In Drupal we can open a modal is two ways, either with HTML:

<a class="use-ajax profile-page-link" data-dialog-type="modal" href="/node/1" data-dialog-options="{&quot;width&quot;:800}">Open Modal</a>

Or with JS:

let ajaxSettings = {
  url: 'node/1',
  dialogType: 'modal',
  dialog: { width: 800 },
};
let ajaxObject = Drupal.ajax(ajaxSettings);
ajaxObject.execute();

Once the modal is open I would like to attach an event to the close button so I can drop a cookie on the close event to show the visitor has seen the modal and not show it to them again.

The close button has the class ui-dialog-titlebar-close but this is added after the initial page load so to attach an event we would need a dynamic click handler such as:

$('body').on('click', '.ui-dialog-titlebar-close', function() {
    alert('close button was clicked 2');
});

However this event never fires. This ctools issue mentions the same thing and has a solution involving binding to the CToolsCloseModalBehaviors event, however that was 6 years ago and I'm using D9 with no ctools so need to find a new solution.

When I inspect the attached events on the close button I can see jquery.ui/ui/widget-min.js r() and an anonymous function in jquery.min.js. Using non minified vs would help but not sure how to do that?

1

In core dialog.js code I've found a following lines of code.

$(window).trigger('dialog:afterclose', [dialog, $element]);

and

$(window).trigger('dialog:beforeclose', [dialog, $element]);

Means that it is possible to assign event listener to these events using the following code sample:

$(window).on('dialog:afterclose', (e) => {
  console.log(e);
});

P.S. Just don't forget to put it into Drupal behaviors and use .once to ensure that event listeners won't attach multiple times.

1

The clue was seeing the Drupal's modal just uses jquery widgets. So a simple Google for "jquery widget close event" lead me to this SO answer.

So the solution is:

$('#drupal-modal').on('dialogclose', function(event) {
    alert('closed');
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.