Problem
Recently I needed to add a popup message to a preexisting custom Drupal 8 theme. I wanted to use the core Dialog API for consistency, but the theme wasn't set up to use the library yet.
Solution
These are rough notes from the process. They may need some tweaking to work for your case.
Add drupal.dialog
dependency to the theme
If your theme doesn't already include the core/drupal.dialog
library, you'll need to add it to the theme's libraries.yml
file.
You may want to refine this to load only in certain situations, but for starters it can go in the global_styles
section.
dependencies:
# Library is defined in `core/core.libraries.yml`.
- core/drupal.dialog
Add the HTML
At this point, you can create a simple custom block with this HTML:
<div class="popup-simple" title="Popup Title" style="display:none">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
</div>
Note that the modal title will be take from the title
attribute by default.
Add the JavaScript
Create the file
Create a file in your theme directory at the path js/popup.js
with the following contents.
/**
* @file
* Contains the definition of the behaviour jsPopupSimple.
*/
(function ($, Drupal) {
'use strict';
/**
* Attaches the JS Popup Simple behavior.
*/
Drupal.behaviors.jsPopupSimple = {
attach: function (context, settings) {
$(context).find('.popup-simple').once('popped').each(function (i, popupElement) {
var myPopup = Drupal.dialog(popupElement);
myPopup.showModal();
});
}
};
})(jQuery, Drupal);
Include the javascript file in the theme
In the theme's libraries.yml
file, add a line to the js
section as so.
You may need to add the js
section. You may want to refine this to load only in certain situations, but for starters it can go in the global_styles
section.
js:
js/popup.js: {}
After you clear the caches and reload the page, you should see the popup.
Taking it further
You can also create a custom block type with a theme template, so that the markup is automatically structured for the JavaScript. I'll demonstrate this in Part 2.