Skip to main content

Ajax Live Search Implementation

By SamK
0
0 recommends
Ajax-Live-Search-Implementation

In this tutorial, you'll learn how to create an ajax based live search system by using HTML and JavaScript, as shown here.

AJAX Live Search System Demo

HTML

<!DOCTYPE html>
<html> 
<head>
  <title>Simple Live Search</title>
  <!-- The title of the webpage, displayed on the browser tab -->
</head>
<body>
  <!-- Heading for the live search feature -->
  <h1>Simple Live Search</h1>
  <!-- Input field for entering the search query -->
  <input type="text" id="search-box" placeholder="Search...">
  <!-- Placeholder text provides a hint to the user -->
  <!-- Unordered list where the search results will be displayed dynamically -->
  <ul id="results"></ul> 
</body>
</html>

JavaScript

// Get references to the search input box and results container
const searchBox = document.getElementById('search-box');
const results = document.getElementById('results');

// Array of data to be searched
const data = ['JavaScript', 'Python', 'React', 'Node.js', 'Vue.js'];

// Variable to store the debounce timer
let timer;

// Add an event listener to the search input box for the 'input' event
searchBox.addEventListener('input', () => {
    // Clear any existing timer to debounce the search functionality
    clearTimeout(timer);

    // Set a new debounce timer
    timer = setTimeout(() => {
        // Get the current query entered in the search box and convert it to lowercase
        const query = searchBox.value.toLowerCase();

        // Clear any previous search results
        results.innerHTML = '';

        // Check if the query is not empty
        if (query) {
            // Filter the data array to find items matching the query
            data.filter(item => item.toLowerCase().includes(query))
                .forEach(item => {
                    // Create a new <li> element for each matching item
                    const li = document.createElement('li');
                    li.className = 'result'; // Add a CSS class for styling

                    // Highlight the matching part of the item using a regular expression
                    li.innerHTML = item.replace(
                        new RegExp(query, 'gi'), // Case-insensitive matching
                        match => `<span class="highlight">${match}</span>` // Wrap matches in a <span>
                    );

                    // Append the <li> element to the results container
                    results.appendChild(li);
                });
        }
    }, 300); // Delay the search by 300ms for better performance (debouncing)
});
Category(s)
Topic(s)