JavaScript
window.addEventListener("onload", function(e){
document.querySelector('searchbar').addEventListener('click', search_album()) //adds a listener for the click event, which runs the function search_album()
document.querySelector('searchbar').addEventListener('blur', hide_results()) //adds a listener for the blur event, where the user loses focus from the input field, running the function hide_results()
});
function search_album() { //function to find the album via search bar
let input = document.getElementById('searchbar').value //input is the searchbar value
input = input.toLowerCase(); //turned into lowercase
let x = document.getElementsByClassName('albums'); // and x is the list of albums with the same class name
for (i = 0; i < x.length; i++){ //looping around for the number of albums in the list found in the php page
if (!x[i].innerHTML.toLowerCase().includes(input)) { //checking that the value entered is not found in the list of albums in the php page
//do not display the list of items that matches
}
else{
x[i].style.display = 'list-item'; //display the list of items that matches
}
}
}
function hide_results() { //function to run when the user click anywhere else in the page, not in the input field
let listItems = document.getElementById('list');
listItems.style.display = 'none'; //hide the results list
document.getElementById("searchbar").value = ""; //empty input field
}
HTML Code
<input id="searchbar" type="text" name="search" placeholder="Search Something..."
onkeyup="search_album()" onblur="hide_results()">
<ol id="list">
<li class="albums" id="#red"><a href="#red" class="link">Red - Taylor Swift</a></li>
<li class="albums" id="#allartists"><a href="artists.php" class="link">All Artists</a></li>
<li class="albums" id="#allalbums"><a href="albums.php" class="link">All Albums of all Artists</a></li>
<li class="albums" id="#taylor"><a href="taylorswift.php" class="link">About Taylor Swift</a></li>
<li class="albums" id="#taylor"><a href="tayloralbums.php" class="link">Taylor Swift Albums</a></li>
<li class="albums" id="#gigs"><a href="gigs.php" class="link">Upcoming GIGS</a></li>
</ol>
I was trying to make a searchbar so the user could enter any key and matching results would start to show up based on if the letter they entered is found in the word, hiding the results when the user clicks outside of the searchbar, showing the results again if inputting letters again, and allowing this process to repeat.