-1

I'm working on a dashboard with Node.js, using express, however, sometimes I generate lists that are extremely long and I want to break them in pages of 20 items, people will have buttons to go to the previous/next page, but I don't know what would be the ideal way to replace the HTML from the list so it shows the 20 previous/next items (depending on which button they press).

I'm using Bootstrap 3.3.7 and jQuery 3.2.1, but I can also use AJAX if needed (requesting data from a local API endpoint). And express 4.15.3 for Node.js.

The data I use to generate the list is an Array of Objects (JSON).

1 Answers1

0

The solution was easier than I thought, I download the array of objects and assign it to an array, then, use jQuery.html(), jQuery.map() and Array.slice() to create the page with 'x' amount of items. When clicking on one of both buttons, it'll change the page and re-slice the array to show the previous/next page.

<div class="container">
    <div class="col-md-8 col-md-offset-2">
        <nav aria-label="guildPager">
            <ul class="pager">
                <li id="previousPage" class="previous"><span aria-hidden="true">&larr;</span></li>
                <li id="nextPage" class="next"><span aria-hidden="true">&rarr;</span></li>
            </ul>
        </nav>
        <div id="guildList"></div>
    </div>
</div>

<script>
    var arr = [{...}, {...}, ..., {...}];
    var page = 0;
    var amount = 20;
    var pages = Math.ceil(arr.length / amount);

    function pagify() {
        if (page === 0 && !$("#previousPage").hasClass("disabled")) $("#previousPage").addClass("disabled");
        else if ($("#previousPage").hasClass("disabled")) $("#previousPage").removeClass("disabled");

        if (page === pages - 1 && !$("#nextPage").hasClass("disabled")) $("#nextPage").addClass("disabled");
        else if ($("#nextPage").hasClass("disabled")) $("#nextPage").removeClass("disabled");

        $("#guildList").html($.map(arr.slice(page * amount, (page * amount) + amount), (a) => {
            return `<h4>${a.name}<small> ${a.users} members.</small></h4><hr></hr><br />`;
        }));
    }
    pagify();

    $("#nextPage").click(function() {
        if ($(this).hasClass("disabled")) return;
        page++;
        pagify();
    });
    $("#previousPage").click(function() {
        if ($(this).hasClass("disabled")) return;
        page--;
        pagify();
    });
</script>