Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active June 14, 2023 14:03
Show Gist options
  • Save marklchaves/c4a73ac26cdcabc6fdbc9c8244cde221 to your computer and use it in GitHub Desktop.
Save marklchaves/c4a73ac26cdcabc6fdbc9c8244cde221 to your computer and use it in GitHub Desktop.
Popup Maker: A workaround to fix the alternate close methods not working on back-to-back popups.
<?php // Ignore this first line when copying to your child theme's functions.php file.
/**
* Listen for alternate close
*
* A workaround to fix the alternate close methods not working on back-to-back popups.
*
*/
function listen_for_alternate_close() { ?>
<script type="text/javascript">
/*
* Listen for:
* 1) a click outside the popup content div tag
* 2) the esc key
* 3) the f4 key
*/
jQuery(document).ready(function($) {
const pumPrefix = '#pum-';
const popupIdArray = ['1234', '4567', '7890']; // Change to your popup IDs.
let popupId = ''; // Need this to be a global because altCloseEventHandler() needs it.
function altCloseEventHandler(e) {
const popupContentDiv = $(`#popmake-${popupId}`);
if ((popupContentDiv.has(e.target).length === 0) || // Outside the popup content.
(e.keyCode === 27) || // The "Esc" key (27).
(e.keyCode === 115)) // The "F4" key (115).
{
console.log(`Popup ${popupId}: You clicked outside the popup, pressed esc, or pressed F4.`);
PUM.close(popupId);
} // if
} // altCloseEventHandler()
function listenForClose(popupSelector) {
$(document).on(`click.${popupId} keyup.${popupId}`, altCloseEventHandler);
}
// Just to be safe.
function turnOffCloseListener(popupId) {
$(document).off(`click.${popupId} keyup.${popupId}`, altCloseEventHandler);
console.log(`Should've turned off close listener for popup ${popupId}`);
}
// Prep all listeners for each popup.
$.each(popupIdArray, function(i, val) {
const popupSelector = pumPrefix + val;
console.log(`Setting close listeners for ${popupSelector}.`);
$(popupSelector).on('pumAfterOpen', function () {
popupId = val; // Set the global popup ID.
listenForClose(popupSelector);
});
console.log(`Setting up listeners to remove close listeners for ${popupSelector}.`);
$(popupSelector).on('pumAfterClose', function () {
turnOffCloseListener(val);
});
}); // $.each()
}); // jQuery()
</script>
<?php }
add_action( 'wp_footer', 'listen_for_alternate_close', 500 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment