Skip to content

Instantly share code, notes, and snippets.

@drubb
Last active October 24, 2024 09:44
Show Gist options
  • Save drubb/8ef8366a10b24bbddb2ca57e4a7bc075 to your computer and use it in GitHub Desktop.
Save drubb/8ef8366a10b24bbddb2ca57e4a7bc075 to your computer and use it in GitHub Desktop.
Drupal behavior that supports opening cookie banner links of the module drupal/cookies inside ajax modals
(function (Drupal, once) {
Drupal.behaviors.cookies = {
attach: function (context, settings) {
once('cookies', 'body', context).forEach(function () {
// Callback function to execute when the cookies banner is added.
const callback = (mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1 && node.classList.contains('cookiesjsr-banner')) {
// Find all links in the child elements of this node.
// They are inside a div with class "cookiesjsr-links".
// Add click event listeners to each link.
const links = node.querySelector('.cookiesjsr-links').querySelectorAll('a');
links.forEach(link => {
// Remove the 'target' attribute from each link.
link.removeAttribute('target');
// Add a click event listener to each link.
link.addEventListener('click', function (event) {
// Prevent the default action of the link.
event.preventDefault();
// Open the link in a modal dialog.
Drupal.ajax({
url: this.getAttribute('href'),
dialogType: 'modal',
dialog: { width: 800 },
}).execute();
});
});
}
});
}
}
};
// Create a mutation observer instance, observing the body element.
const observer = new MutationObserver(callback);
observer.observe(document.body, { childList: true, subtree: true });
});
},
};
})(Drupal, once);
@drubb
Copy link
Author

drubb commented Oct 24, 2024

Dependencies:

- core/drupal.dialog.ajax
- core/once

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment