Me gratter la tête sur celui-ci. J'aimerais pouvoir appliquer un filtre basé sur une balise. J'utilise l'API poke et les données s'affichent et les trient par ID. Ce que j'aimerais faire, c'est que l'utilisateur sélectionne le "type" si pokemon à partir de la balise et que le filtre de page soit basé sur cela (en gardant le tri). Si l'utilisateur ne sélectionne rien, il affichera simplement les 150.

Je m'excuse d'avance d'être un noob total !

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Quick's Pokedex</title>
        <link rel="stylesheet" href="style.css" />
        <link rel="stylesheet" href="/css/animate.css" />
        <link href="https://fonts.googleapis.com/css?family=Rubik&display=swap" rel="stylesheet"/>
        <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.12.1/css/all.css" integrity="sha384-TxKWSXbsweFt0o2WqfkfJRRNVaPdzXJ/YLqgStggBVRREXkwU7OKz+xXtqOU4u8+" crossorigin="anonymous">
    </head>
    <body>
        <div class="header">
            <img src="/assets/img/two.png" alt="Pokemon Logo" height="500" class="animated fadeInLeftBig logo" id="logo">
        </div>
        <div class="container">
            <h3 class="full-experience">Get the full experience!    <i class="fas fa-level-down-alt"></i></h3>
            <audio class="audio-player" loop src="/assets/audio/pokemon.mp3" controls> Error: your web browser does not support this audio player. </audio>
            <h1 class="quicks-h1">Quick's Pokedex</h1>
            <div class="sorting">
                <h2>Sorting</h2>
                <p>Select at least one type</p>
                <div class="custom-select" style="width:200px;">
                    <select>
                    <option value="0">Select Type:</option>
                    <option value="1">Bug</option>
                    <option value="2">Dragon</option>
                    <option value="3">Electric</option>
                    <option value="4">Fairy</option>
                    <option value="5">Normal</option>
                    <option value="6">Psychic</option>
                    <option value="7">Fighting</option>
                    <option value="8">Water</option>
                    <option value="9">Fire</option>
                    <option value="10">Flying</option>
                    <option value="11">Ice</option>
                    <option value="12">Poison</option>
                    <option value="13">Rock</option>
                    <option value="14">Grass</option>
                    <option value="15">Ground</option>
                    </select>
                </div>
                <br>
                <div class="custom-select" style="width:200px;">
                    <select><option value="16">Sort By:</option>
                        <option value="17">Name</option>
                        <option value="18">ID</option>
                        </select>
              </div>
              <br>
              <button class="sort-btn">GO!</button>
            </div>
        <div class="pokedex-div">
            <ul class="pokedex" id="pokedex"></ul>
        </div>
    </div>
<script src="app.js"></script>
<script src="dropdown.js"></script>
    </body>
</html>

Voici l'app.js que j'ai essayé en bas de configurer le filtrage, mais je n'arrive pas à le comprendre.

// //Main API Call//

const pokedex = document.getElementById('pokedex');
const fetchPokemon = () => {
    const promises = [];
    for (let i = 1; i <= 150; i++) {
        const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        promises.push(fetch(url).then((res) => res.json()));
    }
    Promise.all(promises).then((results) => {
        const pokemon = results.map((result) => ({
            name: result.name,
            image: result.sprites['front_default'],
            type: result.types.map((type) => type.type.name).join(', '),
            id: result.id
        })).sort((a, b) => a.id > b.id ? 1 : -1);
        displayPokemon(pokemon);
    });
};
const displayPokemon = (pokemon) => {
    const pokemonHTMLString = pokemon
        .map(
            (pokeman) => `
    <li class="card">
        <img class="card-image" src="${pokeman.image}"/>
        <h2 class="card-title">${pokeman.id}. ${pokeman.name}</h2>
        <p class="card-subtitle">Type: ${pokeman.type}</p>
    </li>
`
        )
        .join('');
    pokedex.innerHTML = pokemonHTMLString;
};
fetchPokemon();

const filterPokemon = pokemon.filter() => {
    const myDropDown = document.querySelector('#myDropDown')
}

J'ai aussi un dropdown.js... Je doute que quelqu'un en ait besoin mais c'est ici :

var x, i, j, selElmnt, a, b, c;
/* Look for any elements with the class "custom-select": */
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  /* For each element, create a new DIV that will act as the selected item: */
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /* For each element, create a new DIV that will contain the option list: */
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < selElmnt.length; j++) {
    /* For each option in the original select element,
    create a new DIV that will act as an option item: */
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
        /* When an item is clicked, update the original select box,
        and the selected item: */
        var y, i, k, s, h;
        s = this.parentNode.parentNode.getElementsByTagName("select")[0];
        h = this.parentNode.previousSibling;
        for (i = 0; i < s.length; i++) {
          if (s.options[i].innerHTML == this.innerHTML) {
            s.selectedIndex = i;
            h.innerHTML = this.innerHTML;
            y = this.parentNode.getElementsByClassName("same-as-selected");
            for (k = 0; k < y.length; k++) {
              y[k].removeAttribute("class");
            }
            this.setAttribute("class", "same-as-selected");
            break;
          }
        }
        h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
    /* When the select box is clicked, close any other select boxes,
    and open/close the current select box: */
    e.stopPropagation();
    closeAllSelect(this);
    this.nextSibling.classList.toggle("select-hide");
    this.classList.toggle("select-arrow-active");
  });
}

function closeAllSelect(elmnt) {
  /* A function that will close all select boxes in the document,
  except the current select box: */
  var x, y, i, arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  for (i = 0; i < y.length; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i)
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < x.length; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}

/* If the user clicks anywhere outside the select box,
then close all select boxes: */
document.addEventListener("click", closeAllSelect);\
1
teamallnighter 11 févr. 2020 à 22:38

1 réponse

Meilleure réponse

Filtré par type électrique par exemple :

const pokedex = document.getElementById('pokedex');
const fetchPokemon = () => {
  const promises = [];
  for (let i = 1; i <= 150; i++) {
    const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
    promises.push(fetch(url).then((res) => res.json()));
  }
  Promise.all(promises).then((results) => {
    const pokemon = results.map((result) => ({
      name: result.name,
      image: result.sprites['front_default'],
      type: result.types.map((type) => type.type.name).join(', '),
      id: result.id
    })).sort((a, b) => a.id > b.id ? 1 : -1);
    console.log('sadfa',pokemon)
    const filteredPokemonsByType= pokemon.filter(x=>x.type==='electric');
    console.log('Filtered by eletric', filteredPokemonsByType);

  });
};

fetchPokemon()

Voici votre exemple complet avec la liste déroulante : https://jsfiddle.net/fkq43gbu/

1
Eugen Sunic 11 févr. 2020 à 21:10