theonlychase
3/28/2019 - 6:20 PM

Add Loading Animation while fetching data

Also, call same function with two different buttons

<div id="btns" class="column is-12-mobile">
  <h4 class="title is-4">Click a button to display male or female data!</h4>
  <a id="male" class="button is-large is-link is-outlined">Male</a>
  <a id="female" class="button is-large is-danger is-outlined">Female</a>
</div>

<script>
  // Loading Spinner
  const loader = `<div class="loader"></div>`;

  // Add event listener
  var el = document.getElementById('btns');
  el.addEventListener("click", getData, false);

  function getData(e) {

    // Get id of element
    let id = e.target.id;

    // Check if the id matches
    if (id === "male" || id === "female") {

      // Add Loader while data is being fetched
      document.getElementById('list').innerHTML = loader;

      // Fetch data
      fetch(`https://randomuser.me/api/?gender=${id}&results=9`)
        .then(response => response.json())
        .then(data => {
          const results = data.results;

          const markup = `
            ${results.map(result => 
              `<div class="column is-4-desktop is-12-mobile is-6-tablet">
                <div class="card hvr-underline-from-center">
                  <div class="card-content is-capitalized">
                      <div class="media">
                        <div class="media-left">
                          <figure class="image is-48x48">
                            <img src="${result.picture.large}" alt="Placeholder image">
                          </figure>
                        </div>
                        <div class="media-content">
                          <p class="title is-4">${result.name.first} ${result.name.last}</p>
                          <a href="mailto:${result.email}" class="subtitle is-6">${result.email}</a>
                        </div>
                      </div>
                  </div>
                </div>
              </div>`
            ).join("")}
          `;
          // Replace Loader Once the Data is returned 
          document.getElementById("list").innerHTML = markup;
        })
        // Catch errors
        .catch(err => {
          console.error(err);
        })
    }
  }
</script>