How to Create a Search Menu to Filter Links with JavaScript

A search menu is a powerful tool for a website to allow users to easily find the content they are looking for.

With the help of JavaScript, we can create a search menu that filters links based on user input.

This tutorial will show you how to create a dynamic search menu using JavaScript.


HTML Markup

To create the search menu, we first need to set up the HTML structure.

The basic structure includes an input field and a list of links.

We can wrap both of these elements in a container with an id that we can use to reference it in our JavaScript code.

<div id="search-container">
  <input type="text" id="search-input">
  <ul id="search-list">
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
    <!-- Add as many links as needed -->
  </ul>
</div>

JavaScript Code

Next, we will add the JavaScript code to make our search menu dynamic.

We will use the input event to listen for changes in the input field and then filter the links based on the user’s input.

const input = document.querySelector('#search-input');
const list = document.querySelector('#search-list');

input.addEventListener('input', function() {
const searchTerm = input.value.toLowerCase();
const links = list.getElementsByTagName('a');

Array.from(links).forEach(function(link) {
const linkText = link.textContent.toLowerCase();
if (linkText.indexOf(searchTerm) !== -1) {
link.parentElement.style.display = 'block';
} else {
link.parentElement.style.display = 'none';
}
});
});

Explanation

In the JavaScript code, we first select the input field and the list of links using querySelector.

Then, we use the addEventListener method to listen for changes in the input field.

When the input event is triggered, we get the search term from the input field and convert it to lower case for easier comparison.

Then, we get all the links from the list using getElementsByTagName and convert it to an array using Array.from.

Next, we loop through each link using the forEach method and compare the link text to the search term.

If the search term is found in the link text, we set the display property of the link’s parent element (the li element) to block, making it visible.

If the search term is not found, we set the display property to none, hiding it.


Conclusion

With just a few lines of JavaScript code, we have created a dynamic search menu that allows users to filter links based on their input.

This can greatly improve the user experience on your website and make it easier for users to find the content they are looking for.