Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active February 20, 2025 04:30
Show Gist options
  • Save marklchaves/7c23a9928636a476aa29043bb6e8ac10 to your computer and use it in GitHub Desktop.
Save marklchaves/7c23a9928636a476aa29043bb6e8ac10 to your computer and use it in GitHub Desktop.
Load custom jQuery in the footer that closes a popup on scroll
<?php // Ignore this first line when copying to your child theme's functions.php file.
/**
* Close a popup on a window scroll event.
*/
function close_popup_on_scroll() { ?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
// Set up your constants.
const popupID = 630, // Change to your popup ID.
scrlThresh = 3; // Adjust the scroll threshold if needed (0 means hide immediately).
// Listen for after the popup opens.
$(document).on('pumAfterOpen', `#pum-${popupID}`, function () {
// While the popup is open, listen for scrolls.
$(window).scroll(function() {
if ($(this).scrollTop() > scrlThresh) { // If this is true, we got a scroll hit!
PUM.close(popupID); // Close the popup.
$(window).off("scroll"); // Clean up.
console.log(`Popup ${popupID} says seeeee yaaaa 🙌🏼.`); // Debug only. Remove for production.
} // if
}); // Scroll listener
}); // After open listener
}); // jQuery
</script>
<?php }
add_action( 'wp_footer', 'close_popup_on_scroll', 500 ); // Load the script in the footer with a "late" priority.
// You can add the PHP code snippet to your child theme's <code>functions.php</code> file or with a third-party plugin such as <a href='https://wordpress.org/plugins/my-custom-functions/'>My Custom Functions</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment