Tom Nolan Tom Nolan - 1 year ago 82
Javascript Question

How turn a list of items in to a "multi-page" list with jquery

I have a website that dynamically creates a list of posts, and I don't have access to the function that creates the content, so I have to work with what is outputted.

<div id="wrap">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 20</div>
<div>Item 21</div>

The function creates 21 items in a list-format (one on top of the other). What I'm looking to achieve is maybe only have 7 visible at a time, and have arrow navigation to shuffle through the various sets of items.

$("#wrap > div").slice(0,7).css("background","yellow");
$("#wrap > div").slice(7,14).css("background","red");
$("#wrap > div").slice(14,21).css("background","blue");

I've been able to target the sets of 7, but as far as how to hide and scroll through the sets, I'm a bit lost.

Any help would be greatly appreciated

Answer Source


var page = 1;
$("#wrap > div").slice(0, 7).addClass('page1').css("background", "yellow");
$("#wrap > div").slice(7, 14).addClass('page2').css("background", "red").hide();
$("#wrap > div").slice(14, 21).addClass('page3').css("background", "blue").hide();
var maxPage = 3;
$('.next').on('click', function() {
  if (page < maxPage) {
    $("#wrap > div:visible").hide();
    $('.page' + ++page).show();
$('.prev').on('click', function() {
  if (page > 1) {
    $("#wrap > div:visible").hide();
    $('.page' + --page).show();
<script src=""></script>
<div id="wrap">
    <div>Item 1</div>
    <div>Item 2</div>
    <div>Item 3</div>
    <div>Item 4</div>
    <div>Item 5</div>
    <div>Item 6</div>
    <div>Item 7</div>
    <div>Item 8</div>
    <div>Item 9</div>
    <div>Item 10</div>
    <div>Item 11</div>
    <div>Item 12</div>
    <div>Item 13</div>
    <div>Item 14</div>
    <div>Item 15</div>
    <div>Item 16</div>
    <div>Item 17</div>
    <div>Item 18</div>
    <div>Item 19</div>
    <div>Item 20</div>
    <div>Item 21</div>
<div class="next">Next</div>
<div class="prev">Prev</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download