3

By adding use-ajax to a link we can open a modal using the Drupal ajax library as per the docs.

E.g.

<a class="use-ajax" 
    data-dialog-options="{&quot;width&quot;:400}" 
    data-dialog-type="modal" 
    href="/node/1">
    First article displayed in modal dialog.
</a>

This will use the ajax library to fetch node/1 and then display it in a modal.

There is also a Dialog API for JavaScript which allows opening modals using JavaScript.

E.g.

var myDialog  = Drupal.dialog(ADOMElement, settings);
myDialog.show();

The problem with this API is you need to pass in a existing DOM element.

My question is can I trigger opening a modal with JavaScript and utalise the internal Drupal ajax library to actually fetch the content?

E.g Can I do something like this?

var myDialog  = Drupal.dialog('/node/1', {useAjax: true});
myDialog.show();

I could just create an html link as per my first code block, hide it with css, and then trigger a click on it with JS but this seems a bit hacky - there must be a way to trigger this action using pure JS.

1 Answer 1

6

You can trigger Ajax in custom javascript. See How to Trigger Existing, Non-Form Ajax from JavaScript Event

In your case an Ajax dialog:

var ajaxSettings = {
  url: '/node/1',
  dialogType: 'modal',
  dialog: { width: 400 },
};
var myAjaxObject = Drupal.ajax(ajaxSettings);
myAjaxObject.execute();
1
  • This works perfectly, but how do you attach behaviours to this modal ?
    – Teenage
    Jul 4, 2022 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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