My current script allows you to add a card some info about its content by clicking on the result of a search bar.
The objective is to create a sort of movies list. However, I do not know how, where or if I should implement a loop to add multiple cards, instead of replacing one.
My biggest issue is that after clicking on the result item, the active card is replaced by the new one.
The first function loads the content based on an API. It basically clears the search bar after clicking on the item shown through the research. It also calls the function responsible for adding a div (a card with the movie informations) to the HTML.
function loadContentDetails(){
const searchListContent = searchList.querySelectorAll('.search-list-item');
searchListContent.forEach(content => {
content.addEventListener('click', async () =>{
searchList.classList.add('hide-search-list');
searchBar.value = "";
const result = await fetch(`http://www.omdbapi.com/?i=${content.dataset.id}&apikey=60ee3e91`);
const contentDetails = await result.json();
displayContentDetails(contentDetails);
});
});}
The second function creates a new card based on what the user selected through the search bar.
function displayContentDetails(details){
cardsGroupFlex.innerHTML = `
<div >
<img src="${(details.Poster != "N/A") ? details.Poster: "resources/img-not-found.png"}" alt="" />
<div >
<p >${details.Title}</p>
<p> ${(details.Plot)} </p>
</div>
</div>
`;}
I would much appreciate your help.
CodePudding user response:
Change cardsGroupFlex.innerHTML =
to cardsGroupFlex.innerHTML =
(add a " " sign before the "="). This will concatenate a new card to the innerHTML rather than replacing the innerHTML with the new card:
cardsGroupFlex.innerHTML = `
<div >
<img src="${(details.Poster != "N/A") ? details.Poster: "resources/img-not-found.png"}" alt="" />
<div >
<p >${details.Title}</p>
<p> ${(details.Plot)} </p>
</div>
</div>
`;
CodePudding user response:
A simple solution is to instead of setting the innerHTML
of cardsGroupFlex
, you could append the card to the end of the innerHTML
.
// instead of
cardsGroupFlex.innerHTML = `...`
// appending with =
cardsGroupFlex.innerHTML = `...`
However if you're going to implement a feature like deleting or editing the cards, you're going to need to have a global array of the card's details, and looping over all of them inside displayContentDetails
.
This solution could also make use of appending to the end of a string.
function displayContentDetails(){
let newInner = ''
for (const details of globalCards) {
inner = `
<div >
<img src="${(details.Poster != "N/A") ? details.Poster: "resources/img-not-found.png"}" alt="" />
<div >
<p >${details.Title}</p>
<p> ${(details.Plot)} </p>
</div>
</div>
`
}
}
CodePudding user response:
One quick note: don't use searchList.classList.add as a function/method. It's a property. So do as following to add classes.
searchList.classList.add = 'hide-search-list';
This is just from a quick observation on your code.