This code creates a dynamic search filter using HTML, CSS, and pure JavaScript. It allows users to filter a list of names by typing in a search box. The HTML sets up the search input and an empty list. The CSS styles the search box and list items for better appearance. The JavaScript handles the core functionality: displaying the list of users and filtering them based on the search query. This feature helps create searchable lists on web pages without relying on external libraries.
You can use this code on any webpage that requires a searchable list, such as user directories, product lists, or contact lists. One benefit is that it improves user experience by allowing quick and easy searching without needing to reload the page.
How to Create Search Filter In HTML CSS and Pure JavaScript
1. First, create a basic HTML structure with an input field for the search box and an unordered list for displaying the items.
<input type="text" placeholder="Search Users" id="filter_users"/> <ul id="users-list"> </ul>
2. Next, add CSS to style the search box and the list items. This improves the appearance and usability of the search filter.
#filter_users{ width:100%; padding:10px; max-width: 360px; box-sizing: border-box; } #users-list{ margin:0; padding:0; } #users-list li{ list-style:none; padding:10px; margin:5px 0; border: 1px solid #e4e4e4; }
3. Now, add the JavaScript to handle displaying and filtering the list of users. This code will dynamically update the list based on the user’s input.
var users = [ 'Goku', 'Naruto', 'Ichigo', 'Flash', 'Batman', 'Sherlock Holmes', 'Khaleesi', 'Steve Fox' ]; ul = document.getElementById("users-list"); var render_lists = function(lists){ var li = ""; for(index in lists){ li += "<li>" + lists[index] + "</li>"; } ul.innerHTML = li; } render_lists(users); // lets filters it input = document.getElementById('filter_users'); var filterUsers = function(event){ keyword = input.value.toLowerCase(); filtered_users = users.filter(function(user){ user = user.toLowerCase(); return user.indexOf(keyword) > -1; }); render_lists(filtered_users); } input.addEventListener('keyup', filterUsers);
You now have a fully functional search filter implemented with HTML, CSS, and JavaScript. This code can be easily integrated into any webpage that requires a searchable list, enhancing the user experience by allowing quick and easy searches without page reloads.