homebrandbeta

Search HTML / Java Script

Sep 12th, 2024
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.11 KB | Source Code | 0 0
  1. <p><strong>Search the site:</strong></p>
  2.  
  3. <p><input type="text" id="searchQuery" placeholder="Search..." class="wp-block-search__input">
  4.     <button onclick="performSearch()">Search</button></p>
  5.  
  6.     <p><b>Search Results</b></p>
  7.     <ul id="results" style="list-style: disc;list-style-position: inside;"></ul>
  8.  
  9.     <script src="https://<static-host>/search/lunr.js"></script>
  10.     <script>
  11.         // Load the JSON index and create Lunr index
  12.         let idx, documents;
  13.  
  14.         async function loadIndex() {
  15.             const response = await fetch('https://<static-host>/search/blog-json-all.json'); // URL to your JSON index from step 1
  16.             documents = await response.json();
  17.  
  18.             // Create Lunr index
  19.             idx = lunr(function () {
  20.                 this.ref('id');
  21.                 this.field('title');
  22.                 this.field('content');
  23.  
  24.                 documents.forEach(function (doc) {
  25.                     this.add(doc);
  26.                 }, this);
  27.             });
  28.         }
  29.  
  30.         // Perform the search
  31.         async function performSearch() {
  32.             const query = document.getElementById('searchQuery').value;
  33.  
  34.             if (!idx) {
  35.                 await loadIndex(); // Ensure index is loaded
  36.             }
  37.  
  38.             const results = idx.search(query);
  39.  
  40.             // Display the search results
  41.             const resultsContainer = document.getElementById('results');
  42.             resultsContainer.innerHTML = ''; // Clear previous results
  43.  
  44.             if (results.length === 0) {
  45.                 resultsContainer.innerHTML = '<li>No results found<\/li>';
  46.                 return;
  47.             }
  48.  
  49.             results.forEach(result => {
  50.                 const doc = documents.find(d => d.id === result.ref);
  51.                 const listItem = document.createElement('li');
  52.                 listItem.innerHTML = `<a href="${doc.url}">${doc.title}<\/a>`;
  53.                 resultsContainer.appendChild(listItem);
  54.             });
  55.         }
  56.  
  57.         // Load the index when the page loads
  58.         document.addEventListener('DOMContentLoaded', loadIndex);
  59.     </script>
  60. </div>
Advertisement
Add Comment
Please, Sign In to add comment