When using Fancybox with the default WordPress gallery, you may notice that after closing the lightbox, the page unexpectedly scrolls back to the top. This is a common issue caused by the way the browser handles focus events after the lightbox closes.
The Solution
We can easily fix this issue by preventing the default scroll behavior when Fancybox closes. Below is the JavaScript snippet you need to add to your theme’s custom.js file or enqueue it via functions.php.
jQuery(document).ready(function ($) {
// Fancybox close event listener
$(document).on('afterClose.fb', function () {
// Prevent the page from scrolling back to the top
setTimeout(function () {
if (window.history.scrollRestoration) {
window.history.scrollRestoration = 'manual';
}
}, 10);
});
});
How It Works
-
afterClose.fb – This event triggers right after Fancybox closes.
-
setTimeout – A short delay to let the closing animation complete.
-
scrollRestoration = ‘manual’ – This prevents the browser from automatically scrolling to the top after the modal is closed.
Where to Place This Script?
You have two options:
-
Custom JS File (Recommended)
-
Add the script to a file named
custom-fancybox-fix.jsin your theme’sjsfolder. -
Enqueue it in your theme’s
functions.php:function custom_fancybox_fix() { wp_enqueue_script('custom-fancybox-fix', get_stylesheet_directory_uri() . '/js/custom-fancybox-fix.js', array('jquery'), '1.0', true); } add_action('wp_enqueue_scripts', 'custom_fancybox_fix');
-
- Directly in functions.php (Quick Solution)
If you don’t want to use an external JS file, you can add it directly:function custom_fancybox_fix_inline() { ?> <script type="text/javascript"> jQuery(document).ready(function ($) { $(document).on('afterClose.fb', function () { setTimeout(function () { if (window.history.scrollRestoration) { window.history.scrollRestoration = 'manual'; } }, 10); }); }); </script> <?php } add_action('wp_footer', 'custom_fancybox_fix_inline');
Result
After applying this fix, the page will remain at its scroll position when you close the Fancybox lightbox, providing a smoother and more natural user experience.