Home > OS >  VANILLA JS: Show first 4 result of fetch request and show all on click
VANILLA JS: Show first 4 result of fetch request and show all on click

Time:08-11

I have fetch request that displaying all results. I want to show first 4 result and when you click on show all then displaying all results and the same when you click show less then displaying only first 4. Show all button should display how many more results you can show. Here is my code for JS file:

const dateList = document.getElementById('date')


fetch('./test_data.json')
    .then(res => res.json())
    .then(data => {
        let html = "";
        if(data) {
            data.forEach(time => {
                html  = `
                <div>
                  <ul>
                    <li >
                      <span >${moment(time.date).format('YYYY-MM-DD, h:mm a Z')}</span>
                      <div >
                        <svg
                          
                          width="12px"
                          height="18px"
                          viewBox="0 0 12 18"
                          version="1.1"
                          xmlns="http://www.w3.org/2000/svg"
                        >
                          <g
                            id="Credit-Lock"
                            stroke="none"
                            stroke-width="1"
                            fill="none"
                            fill-rule="evenodd"
                          >
                            <g
                              id="2.1-Creditlock-Locked-History-Desktop"
                              transform="translate(-424.000000, -539.000000)"
                              fill="#3E3F42"
                              fill-rule="nonzero"
                            >
                              <g
                                id="bureau"
                                transform="translate(167.000000, 190.000000)"
                              >
                                <g
                                  id="Group"
                                  transform="translate(22.000000, 349.820582)"
                                >
                                  <path
                                    d="M245.5,5.79545455 L244.75,5.79545455 L244.75,3.75 C244.75,1.68 243.07,-1.77635684e-14 241,-1.77635684e-14 C238.93,-1.77635684e-14 237.25,1.68 237.25,3.75 L237.25,5.79545455 L236.5,5.79545455 C235.675,5.79545455 235,6.47045455 235,7.29545455 L235,14.7954545 C235,15.6204545 235.675,16.2954545 236.5,16.2954545 L245.5,16.2954545 C246.325,16.2954545 247,15.6204545 247,14.7954545 L247,7.29545455 C247,6.47045455 246.325,5.79545455 245.5,5.79545455 Z M241,12.5454545 C240.175,12.5454545 239.5,11.8704545 239.5,11.0454545 C239.5,10.2204545 240.175,9.54545455 241,9.54545455 C241.825,9.54545455 242.5,10.2204545 242.5,11.0454545 C242.5,11.8704545 241.825,12.5454545 241,12.5454545 Z M243.325,5.79545455 L238.675,5.79545455 L238.675,3.75 C238.675,2.4675 239.7175,1.425 241,1.425 C242.2825,1.425 243.325,2.4675 243.325,3.75 L243.325,5.79545455 Z"
                                    id="unlock_icon-copy-8"
                                  ></path>
                                </g>
                              </g>
                            </g>
                          </g>
                        </svg>
                        <span >${time.type}</span>
                      </div>
                    </li>
                   </ul>
                  </div>`;
            });
            dateList.classList.remove('notFound');
        } else {
            html = "Sorry, we didn't find any meal!";
            dateList.classList.add('notFound');
        }
        dateList.innerHTML = html
    })

Here is HTML code:

<div>
  <div id="date"></div>
  <p >Show All (5)</p>
</div>

CodePudding user response:

I couldn't get the data that you have, so I used a random free API service for this purpose (p.s. data fetch is a little slow, give it a couple of seconds to load up):

fetch('https://api.publicapis.org/entries')
  .then((response) => response.json())
  .then((data) => displayData(data))

let fetchedData;


function displayData(data, total = 4) {
  fetchedData = data;
  let item = '';

  for (let i = 0; i < total; i  ) {
    item  = `<li>${data.entries[i].API}</li>`;
}
    document.getElementById("item").innerHTML = item;
}

function showAll() {
  displayData(fetchedData, 100)
}
<div>
  <ul>
    <li id="item"></li>
  </ul>
  <button onclick="showAll()">Show All (100)</button>
</div>

CodePudding user response:

With a 'lil bit of CSS this is quite easy. First set up two new CSS classes:

.hidden {
    display: none;
}

.visible {
    display: block;
}

As the names imply one is used to hide an <ul> element, whereas the other actually displays it.

Next simply go over your data elements, create the html elements accordingly and give all the class hidden.

data.forEach(time => {
    let div = document.createElement("div");
    div.innerHTML = `<ul><li><span>${time}</span></li></ul>`;
    div.classList.add("hidden");
    dateList.appendChild(div);
});

Finally we just need a function which displays/hides the element on our needs.

function toggle(showAll) {

        let items = dateList.children;
        for (let a = 0; a < items.length; a  ) {
            items[a].classList.remove(...items[a].classList);
            items[a].classList.add("hidden")
            if (a < 4) {
                items[a].classList.add("visible")
            } else {
                if (showAll) {
                    items[a].classList.add("visible")
                }
            }
        }
    }

The above function goes through all children we've appended to the dateList <div> initially and if showAll is false only the CSS class of the first four elements is switched to ´visible´.

Here's the complete example:

let data = [1, 2, 3, 4, 5, 6, 7];
let dateList = document.getElementById("dateList");
data.forEach(time => {
    let div = document.createElement("div");
    div.innerHTML = `<ul><li><span>${time}</span></li></ul>`;
    div.classList.add("hidden");
    dateList.appendChild(div);
});

document.getElementById("showAll").value = `Show All (${data.length})`;
document.getElementById("showAll").addEventListener("click", () => {
    toggle(true);
});
document.getElementById("showLess").addEventListener("click", () => {
    toggle(false);
});

function toggle(showAll) {
    let items = dateList.children;
    for (let a = 0; a < items.length; a  ) {
        items[a].classList.remove(...items[a].classList);
        items[a].classList.add("hidden")
        if (a < 4) {
            items[a].classList.add("visible")
        } else {
            if (showAll) {
                items[a].classList.add("visible")
            }
        }
    }
}

toggle(false);
.hidden {
    display: none;
}

.visible {
    display: block;
}
<input type="button" id="showAll" /><input type="button" id="showLess" value="Show Less" />
  <div id="dateList"></div>

  • Related