Realtime Search Results for Bricks Builder Overlay Search, WooCommerce Products, WP-REST API

Realtime Search Results for WooCommerce Bricks Builder Overlay Search

it works with wp-rest makes the request from wp-json that is why it is so fast and instant 

You can select the ul with .custom-search-results or list items .custom-search-results li or .custom-search-results a and style it with css.

document.addEventListener('DOMContentLoaded', function () {
    // Get the search input element
    const searchInput = document.querySelector('.bricks-search-overlay .bricks-search-form input');
    const searchForm = document.querySelector('.bricks-search-overlay .bricks-search-form');

    // Create a new ul element to display the product search results and add a custom class for styling
    const resultList = document.createElement('ul');
    resultList.classList.add('custom-search-results'); // Add custom class for styling
    resultList.style.marginTop = '10px'; // Some margin to separate from the search form
    searchForm.insertAdjacentElement('afterend', resultList);

    // Function to fetch product search results from the WooCommerce REST API (targeting products)
    async function fetchSearchResults(query) {
        const response = await fetch(`/wp-json/wp/v2/product?search=${query}`);
        if (response.ok) {
            const data = await response.json();
            return data;
        }
        return [];
    }

    // Function to display product search results
    function displayResults(results) {
        // Clear the current result list
        resultList.innerHTML = '';

        // Loop through the product results and create list items with links
        results.forEach(product => {
            const listItem = document.createElement('li');
            const link = document.createElement('a');
            link.href = product.link;
            link.textContent = product.title.rendered;
            listItem.appendChild(link);
            resultList.appendChild(listItem);
        });
    }

    // Add an event listener to the search input for real-time product search
    searchInput.addEventListener('input', async function () {
        const query = searchInput.value.trim();

        // Perform the product search only if the query has at least 3 characters
        if (query.length >= 2) {
            const results = await fetchSearchResults(query);
            displayResults(results);
        } else {
            // Clear the result list if the query is less than 3 characters
            resultList.innerHTML = '';
        }
    });
});

if you need posts version check this.

Leave the first comment