Prevent auto-scroll on filter changes
Overview
By default, WooCommerce Product Filters automatically scrolls the page to the top of the product grid after a filter is selected. This ensures that customers immediately see the updated results, especially on mobile devices or pages with large headers.
If you prefer to keep the scroll position static when a user interacts with your filters, you can achieve this by adding a small code snippet to your site.
How it works
The plugin uses a built-in event called wcf:products:beforeScroll. By adding a JavaScript listener for this event, we can intercept the scroll command and prevent the browser from moving the page position.
Step-by-step instructions
To prevent the page from scrolling after a filter is applied, follow these steps:
- Copy the following code snippet:
jQuery(function($) { let blockScroll = false document.addEventListener( 'wcf:products:beforeScroll', function() { blockScroll = true setTimeout(function() { blockScroll = false }, 300) }, true ); const originalScrollTo = window.scrollTo window.scrollTo = function() { if (blockScroll) { return } return originalScrollTo.apply(window, arguments) } })
- Add this code to your website. We recommend using a free plugin such as WPCode to safely add JavaScript to your site.
- If using WPCode, create a new snippet, set the Code Type to JavaScript, and ensure it is set to load in the Frontend.
- Save the snippet and clear your website cache.
Troubleshooting
The page still scrolls after adding the code
- Clear Cache: Ensure you have cleared your caching plugin (e.g., WP Rocket) and your browser cache.
- Check Placement: Ensure the script is loading in the footer of your website.
- Syntax Errors: If you are adding this directly to a .js file, ensure you are not nesting it inside another conflicting function.
The code causes an error in my admin dashboard
- This script is intended for the frontend only. If you are using a code snippets plugin, ensure the "Location" or "Insertion" logic is set to Site Wide Header or Footer, and not running in the WordPress admin area.
Related articles
If searching the knowledge base hasn't answered your question, please contact support.