Skip to content

Instantly share code, notes, and snippets.

@divimode-philipp
Last active September 30, 2022 08:33
Show Gist options
  • Save divimode-philipp/630970f9d94d5dc030b2741dbeee2e6b to your computer and use it in GitHub Desktop.
Save divimode-philipp/630970f9d94d5dc030b2741dbeee2e6b to your computer and use it in GitHub Desktop.
Two ways how to display dynamic contents inside a Divi Area. In this sample we only change the URL of an iframe inside the Area, but it's possible to literally change anything inside the Area (e.g. fill out form fields, insert a user-name into a <span>, show/hide a button, etc.)
/**
* Option 1:
* Open an existing Popup and change the URL of an iframe inside the Popup.
*
* Preparation:
* Create a Divi Area (or an On-Page Popup) which contains an iframe.
*
* @param {string} areaId - The ID of an existing Popup or Divi Area.
* @param {string} iframeUrl - The new URL of the iframe inside the Popup.
*/
function openPopup(areaId, iframeUrl) {
var area = DiviArea.getArea(areaId);
if (! area) {
// Bail, because the Popup does not exist.
return;
}
// Note: area.find() is an alias for jQuery.find() to locate an HTML
// element inside the Divi Area.
var iframe = area.find('iframe');
if (iframe.length) {
// Bail, because the Popup does not contain an iframe.
return;
}
// Update the iframe URL and show the Popup.
iframe.prop('src', iframeUrl);
area.show();
}
// Test:
// Test: Open the Divi Area with slug "dynamic"
openPopup('dynamic', 'https://example.com/');
/**
* Option 2:
* Create a Popup on-the-fly with dynamic content and display it
*
* No preparation needed.
*
* @param {string} id - An ID that identifies the Popup contents.
* @param {string} html - The contents of the Popup, as HTML string.
*/
function createAndOpenPopup(id, html) {
var areaId = '_dynamic-' + id;
var area = DiviArea.getArea(areaId);
if (!area) {
// Dynamically create the container inside the Popup.
var inner = jQuery('<div>');
// Use this CSS class to customize the layout of the contents;
// e.g. `.dynamic-popup{ background: #fff; }`
inner.addClass('dynamic-popup');
// Important: To re-use the dynamic Popup, give it a unique ID!
inner.attr('id', areaId);
// Assign the provided HTML to the Popup contents
inner.html(html);
// Define some Divi Area attributes for the dynamic Popup.
var attrs = {};
attrs.maxWidth = '640px';
attrs.position = 'top-center';
// Create the dynamic Popup!
area = DiviArea.register(inner, attrs, 'popup');
}
// Finally, show the Area, if it could be created.
if (area) {
area.show();
}
}
// Test:
createAndOpenPopup('example', '<iframe src="https://example.com/" />');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment