escu.dev
escu.dev

Reputation: 3

I need to create a 'See more pictures' button in JS

I'm creating a gif website, which uses GIPHY API. In this website, I added a "Search bar", where you can type what kind of GIF you are looking for, and the websites returns 12 gifs from GIPHY.

This is my search function:

async function buscarGifs(valorDeInput,tipoRequest1,tipoRequest2,limit,num){
let urlSearch = `https://api.giphy.com/v1/${tipoRequest1}/${tipoRequest2}?api_key=${apiKey}&q=${valorDeInput}&limit=${limit}&offset=${num}&rating=g&lang=es`;
    let response = await fetch(urlSearch);
    return response.json();
}

What I was trying to do, is to create a 'see more' function: When you click the 'See more' button, the limit is modified, and the web shows you 12 more gifs (plus the first 12 gifs from the initial search).

This is how I call the 'buscarGifs' (gif search) function:

inputSearch.addEventListener("keyup", (event)=>{
if(event.keyCode === 13){ //Activa búsqueda con enter.
    printSearch(buscarGifs(inputSearch.value,"gifs","search",1,0),inputSearch.value);//Busca en API e imprime en DOM.
inputSearch.value = ""; //Vaciar casilla de búsqueda.
}

});

How would you do this?

Thx!

Upvotes: 0

Views: 60

Answers (2)

uingtea
uingtea

Reputation: 6554

save current search query, offset and total results

let currentQuery, resultOffset, totalCount;

async function buscarGifs(valorDeInput, tipoRequest1, tipoRequest2, limit, num) {
  let urlSearch = `https://api.giphy.com/v1/${tipoRequest1}/${tipoRequest2}?api_key=${apiKey}&q=${valorDeInput}&limit=${limit}&offset=${num}&rating=g&lang=es`;
  let response = await fetch(urlSearch);
  let results = response.json();
  // update total results
  totalCount = results.pagination.total_count;
  // show hide more button
  if(resultOffset > totalCount){
    alert('no more results, remove more button');
  }
  return results;
}

inputSearch.addEventListener("keyup", (event) => {
  if (event.keyCode === 13) {
    currentQuery = inputSearch.value;
    // new search, reset to 0
    resultOffset = 0;
    printSearch(buscarGifs(currentQuery, "gifs", "search", 12, 0), currentQuery);
    inputSearch.value = "";
  }
})

// the more button
moreButton.addEventListener("click", (event) => {
  resultOffset += 12
  printSearch(buscarGifs(currentQuery, "gifs", "search", 12, resultOffset), currentQuery);
})

Upvotes: 0

Edgardo Rodríguez
Edgardo Rodríguez

Reputation: 536

You might try something like,

showMoreBtn.addEventListener("click", () => { 
  printSearch(buscarGifs(inputSearch.value,"gifs","search",1,0),inputSearch.value);
  inputSearch.value = "";
}

Modify the limit and num params accordingly. I'm not sure why you used 1 and 0 to fetch the first twelve records in the first place.

Upvotes: 0

Related Questions