I created a search bar with vanilla js that loads items from an API array. When I search for the first time, it loads an image, title, and price. but when you type in a second search, the list does not refresh. You also can’t click out of it.
<body>
<input type="text" id="searchBar" onkeyup="getItemList()" class="blgSearch" name="search bar" placeholder="Type In Item"><button id="searchBtn" onclick="btnFunction" type="submit">search</button>
<div id="itemsFilter">
<!-- <div class="item">
<img src="" alt="image"/>
<h2>Item Title</h2>
<div>cost</div></div> -->
</div>
<script src="/search.js"></script>
and script
//connect to API
let path = "<path>";
let devKey = "<key>";
let token = "<token>";
const api = path+ devKey + token;
const url = encodeURI(api)
let itemsList= [];
window.addEventListener('DOMcontentLoaded', loadContent)
//displays loaded content
function loadContent(){
getItemList();
btnfunction();
}
fetch(url)
.then (res => res.json())
.then(data => {console.log(data); itemsList= data})
//activate on keyup
const searchBar = document.getElementById('searchBar');
//activate onclick
// const searchBtn = document.getElementById('searchBtn');
//searchBar.addEventListener("keyup", getItemList);
const itemsFilter = document.getElementById('itemsFilter');
//filter out items by name
function getItemList(){
console.log(itemsList);
let filteredItems= itemsList.rows.filter(item=> item.name.includes(searchBar.value));
//create the filtered items element
filteredItems.forEach(filteredItem => {
let itemDiv = `
<div class="item">
<img src="${filteredItem.picture}" class="filteredImg" alt=""/>
<h2 class="itemName" >${filteredItem.name}</h2>
<div class="itemPrice" >$${filteredItem.base_cost}</div>
</div>
`
itemsFilter.insertAdjacentHTML("beforeend", itemDiv);
});
}
function searchBnt() {
}
any tips?