codex23

search suggestions

Feb 14th, 2025 (edited)
1,905
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 5.17 KB | Source Code | 0 0
  1. export default class SearchFilter {
  2.  
  3.   constructor(inputSelector, buttonSelector, apiEndpoint) {
  4.     /**
  5.      * Constructor: Initializes the search filter by selecting DOM elements,
  6.      * setting the API endpoint, and binding event listeners.
  7.      *
  8.      * @param {string} inputSelector - The selector for the search input element.
  9.      * @param {string} buttonSelector - The selector for the search button element.
  10.      * @param {string} resultsContainerClass - The class name to assign to the results container.
  11.      * @param {string} apiEndpoint - The API endpoint URL for fetching products.
  12.     */
  13.     this.searchField = document.querySelector(inputSelector).value;
  14.     this.searchButton = document.querySelector(buttonSelector);
  15.     this.resultsContainer = document.querySelector(".search-container .searchFilter");
  16.     this.apiEndpoint = apiEndpoint;
  17.  
  18.     // Initialize event listeners for search input and button
  19.     this.searchResults();
  20.   }
  21.  
  22.  
  23.   displayResultsContainer() {
  24.     /**
  25.      * displayResultsContainer
  26.      *
  27.      * Displays the search results container by adding a CSS class.
  28.      *
  29.      * @returns {HTMLElement} The search results container element.
  30.     */
  31.     console.log("displayResultsContainer called");
  32.     this.resultsContainer.classList.add("searchShow");
  33.     return this.resultsContainer;
  34.   }
  35.  
  36.  
  37.   getQuery(term) {
  38.     /**
  39.      * getQuery
  40.      *
  41.      * Retrieves the search term entered by the user.
  42.      *
  43.      * @param {string} term - The raw search term.
  44.      * @returns {string} The processed search term.
  45.     */
  46.     console.log("getQuery called");
  47.     return term;
  48.   }
  49.  
  50.  
  51.   async getProducts(matchingProduct) {
  52.     /**
  53.      * getProducts
  54.      *
  55.      * Asynchronously fetches products from the API endpoint and filters them
  56.      * based on the search term.
  57.      *
  58.      * @param {string} matchingProduct - The search term to filter products.
  59.      * @returns {Promise<Array>} A promise that resolves to an array of matching products.
  60.    */
  61.     console.log("getProducts called");
  62.     let searchTerm = this.getQuery(matchingProduct);
  63.     try {
  64.       const response = await fetch(this.apiEndpoint, { method: "GET" }); // Toets deur 'n ander post type te gebruik.
  65.       if (!response.ok) {
  66.         throw new Error("Failed to fetch products");
  67.       }
  68.       const products = await response.json();
  69.      
  70.       // Filter products whose names include the search term (case-insensitive)
  71.       const matchingProducts = products.filter(product =>
  72.         product.name.toLowerCase().includes(searchTerm.toLowerCase())
  73.       );
  74.       return matchingProducts;
  75.     } catch (error) {
  76.       console.error("Error fetching products:", error);
  77.       return [];
  78.     }
  79.   }
  80.  
  81.  
  82.   async createResults(searchTerm) {
  83.     /**
  84.      * createResults
  85.      *
  86.      * Creates HTML list items for each matching product and appends them to the results container.
  87.      *
  88.      * @param {string} searchTerm - The search term entered by the user.
  89.      * @returns {Promise<Array>} A promise that resolves to the array of matching products.
  90.      */
  91.     console.log("createResults called");
  92.     const matchingProducts = await this.getProducts(searchTerm);
  93.  
  94.     // Clear any existing results
  95.     this.resultsContainer.innerHTML = "";
  96.  
  97.     if (matchingProducts.length === 0) {
  98.       this.resultsContainer.innerHTML = '<li class="result">No results found.</li>';
  99.       return matchingProducts;
  100.     }
  101.  
  102.     // Create a list item for each matching product
  103.     matchingProducts.forEach(product => {
  104.       const listItem = document.createElement("li");
  105.       listItem.classList.add("listItem");
  106.  
  107.       // Create an image element for the product thumbnail
  108.       const imageElement = document.createElement("img");
  109.       imageElement.classList.add("itemThumb");
  110.       imageElement.src = product.images && product.images.length > 0 ? product.images[0].src : "";
  111.       imageElement.alt = product.name;
  112.  
  113.       // Create an anchor element wrapping a header for the product name
  114.       const titleElementHeader = document.createElement("h1");
  115.       titleElementHeader.textContent = product.name;
  116.       const titleElement = document.createElement("a");
  117.       titleElement.classList.add("itemTitle");
  118.       titleElement.href = product.permalink;
  119.       titleElement.appendChild(titleElementHeader);
  120.  
  121.       // Append the image and title to the list item
  122.       listItem.appendChild(imageElement);
  123.       listItem.appendChild(titleElement);
  124.  
  125.       // Append the list item to the results container
  126.       this.resultsContainer.appendChild(listItem);
  127.     });
  128.  
  129.     return matchingProducts;
  130.   }
  131.  
  132.  
  133.   searchResults() {
  134.     /**
  135.      * searchResults
  136.      *
  137.      * Binds the event listener to the search input field so that as the user types,
  138.      * the results container is displayed and the search is performed with a delay.
  139.      */
  140.     console.log("searchResults called");
  141.     this.searchField.addEventListener("keyup", () => {
  142.       console.log("searchResults event called");
  143.       this.displayResultsContainer();
  144.       // Use setTimeout to delay fetching results until user stops typing for 750ms
  145.       setTimeout(() => this.createResults(this.searchField.value), 750);
  146.     });
  147.   }
  148. }
  149.  
Advertisement
Add Comment
Please, Sign In to add comment