Table of Contents & Menu
Navigation

Customizing Modal Event Listeners

You can customize the click and keydown event listener callbacks for modals.

Available since 1.1.13

In older releases of Hyva_Theme, callbacks were not globally exposed and required overriding the page/js/modal.phtml template for customization.
If you are using an older version, please upgrade the theme module.

These callbacks are globally available as:

  • window.hyva.modal.eventListeners.click
  • window.hyva.modal.eventListeners.keydown

For example, to remove the modal's click-away event listener:

document.removeEventListener('click', window.hyva.modal.eventListeners.click)

A common use case is to create modals with a backdrop overlay that cannot be closed by clicking outside or pressing the ESC key.

Wrapping the event listeners

Here's an example of wrapping the keydown event, allowing for further extensions:

(function () {
    // store reference to the original event subscriber function
    const originalListener = window.hyva.modal.eventListeners.keydown;
    // remove the original event subscriber
    document.removeEventListener('keydown', originalListener);
    // declare the new event subscriber function on the global window.hyva.modal.eventListeners object
    window.hyva.modal.eventListeners.keydown = event => {
        console.log('my wrapper', event);
        originalListener(event); // call original listener if needed
    };
    // Activate the new event listener
    document.addEventListener('keydown'', window.hyva.modal.eventListeners.keydown);
})()

Accessing the current modal

Available since Hyvä 1.2.4 and 1.1.24

The window.hyva.modal.peek() method returns the currently active modal instance, or false if no modal is open.

The returned object has several properties:

{
  name: 'the dialog name',
  instance: {the Alpine component object}, 
  focusTarget: DOM element to receive focus after hiding the dialog (or null),
  time: timestamp when the modal was shown, 
};
The name and instance properties can be useful. time and focusTarget are for internal state management only.