How to create: Search Menu
- Previous Page Icon Navigation Bar
- Next Page Search Bar
Learn how to use JavaScript to create a search menu to filter links.
Search/Filter Menu
How to search for links in the navigation menu:
Page Content
Please enter a specific category/link in the search bar to "filter" the search options.
Some text..Some text..Some text..Some text..Some text..Some text..Some text..Some text..
Some other text..Some text..Some text..Some text..Some text..Some text..Some text..Some text..
Some text..
Create a search menu
Step 1 - Add HTML:
<input type="text" id="mySearch" onkeyup="myFunction()" placeholder="Search.." title="Type in a category"> <ul id="myMenu"> <li><a href="#">HTML</a></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> <li><a href="#">PHP</a></li> <li><a href="#">Python</a></li> <li><a href="#">jQuery</a></li> <li><a href="#">SQL</a></li> <li><a href="#">Bootstrap</a></li> <li><a href="#">Node.js</a></li> </ul>
Note:In this demonstration, we use href="#"
because we do not have any linkable pages. In reality, this should be a real URL pointing to a specific page.
Step 2 - Add CSS:
Set the style of the search box and navigation menu:
/* Set the style of search box */ #mySearch { width: 100%; font-size: 18px; padding: 11px; border: 1px solid #ddd; } /* Set the style of navigation menu */ #myMenu { list-style-type: none; padding: 0; margin: 0; } /* Set the style of navigation links */ #myMenu li a { padding: 12px; text-decoration: none; color: black; display: block } #myMenu li a:hover { background-color: #eee; }
Step 3 - Add JavaScript:
<script> function myFunction() { // Declare variables var input, filter, ul, li, a, i; input = document.getElementById("mySearch"); filter = input.value.toUpperCase(); ul = document.getElementById("myMenu"); li = ul.getElementsByTagName("li"); // Loop through all list items and hide those that do not match the search query for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } } </script>
Tip:If you want to perform a case-sensitive search, please remove toUpperCase()
.
Related pages
Tutorial:How to filter a table
Tutorial:How to Filter List
- Previous Page Icon Navigation Bar
- Next Page Search Bar