When using live query functionality with the Query Block, content is dynamically updated without requiring a full page refresh. This means that any custom JavaScript events or third-party libraries that were initially bound to the DOM elements may lose their functionality after the content updates. To address this challenge, the Greyd system provides a custom event that allows developers to re-initialize their code whenever new content is loaded.
The greyd-livequery-success event is automatically fired after each successful live query update and all built-in Greyd features have been re-initialized. This event is dispatched on the specific .wp-block-query wrapper element that contains the updated content, ensuring that you can target your re-initialization code precisely to the affected areas.
To implement event re-initialization, you need to add an event listener that responds to the greyd-livequery-success event. The most effective approach is to attach these listeners during the initial page load using the DOMContentLoaded event. This ensures that your code is ready to respond to live query updates as soon as they occur.
Here’s the basic implementation pattern you should follow:
document.addEventListener('DOMContentLoaded', function() {
const queryBlocks = document.querySelectorAll('.wp-block-query');
queryBlocks.forEach(queryBlock => {
queryBlock.addEventListener('greyd-livequery-success', function(event) {
// Your custom re-initialization code here
console.log('Live query completed for:', event.target);
// Example: Re-initialize a custom library
if (typeof myCustomLibrary !== 'undefined') {
myCustomLibrary.init(event.target);
}
});
});
});When multiple query blocks update simultaneously, such as during responsive breakpoint changes, the event is fired individually for each affected query wrapper. This allows you to handle each block’s re-initialization independently and ensures that your code remains performant even with complex layouts containing multiple live queries.
It’s important to note that the event fires after all built-in Greyd features have already been re-initialized, so you don’t need to worry about conflicts with the core functionality. However, you should ensure that your re-initialization code is idempotent, meaning it can be called multiple times without causing issues, since the event may fire repeatedly as users interact with filters or pagination controls.
For optimal performance, consider scoping your re-initialization code to only the elements within the updated query block rather than reinitializing across the entire page. The event target provides you with the exact query wrapper that was updated, allowing you to limit your operations to the relevant DOM subtree.
This approach is particularly useful for scenarios such as re-initializing image galleries, updating form validations, refreshing analytics tracking, or ensuring that accessibility features continue to function properly with the dynamically loaded content.