Search code examples
javascripthtmljqueryjquery-selectorsresponsive

Improve this "next","previous" script, so that it could go up to atleast 3


I am trying to create a column containing items, within this column you can go to "next" or "prev" page.

This works fine and quick!

Now here my question is

How do I create up to page 8 or even more, so that you could scroll through the pages?.

I am trying something with this, but I somehow cant implement it into html

function next() {
  var nextUrl = "Page + (index+1)";
}

function back() {
  var prevUrl = "Page + (index-1)";
}

Here is my current setup

function show(elementID) {
    var ele = document.getElementById(elementID);
    if (!ele) {
        alert("dit bestaat niet");
        return;
    }
    var pages = document.getElementsByClassName('page');
    for(var i = 0; i < pages.length; i++) {
        pages[i].style.display = 'none';
    }
    ele.style.display = 'block';
}

                	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="Page1" class="page" style="">
    page 1
</div>
<div id="Page2" class="page" style="display:none">
    page 2
</div>



<div class="column-wrapper">
  <div class="pagination paginatioon--full">
  <p> 
<span onclick="show('Page1');">
  <a href='#' class="pagination__prev">prev</a>
</span>
<span onclick="show('Page2');">
  <a href='#'class="pagination__next">next</a>          </span> 
  </p>
  </div>
</div>


Solution

  • You can do something like this :

    var currentPageId = 1;
    var totalpages = $('.page').length;
    
    $('.prev').click(function(e) {
      if (currentPageId > 1) {
        currentPageId--;
        show('Page' + currentPageId);
      }
    });
    $('.next').click(function(e) {
      if (currentPageId < totalpages) {
        currentPageId++;
        show('Page' + currentPageId);
      }
    });
    
    
    
    function show(elementID) {
      var ele = document.getElementById(elementID);
      if (!ele) {
        alert("dit bestaat niet");
        return;
      }
      var pages = document.getElementsByClassName('page');
      for (var i = 0; i < pages.length; i++) {
        pages[i].style.display = 'none';
      }
      ele.style.display = 'block';
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="Page1" class="page" style="">
      page 1
    </div>
    <div id="Page2" class="page" style="display:none">
      page 2
    </div>
    <div id="Page3" class="page" style="display:none">
      page 3
    </div>
    
    <div class="column-wrapper">
      <div class="pagination paginatioon--full">
        <p>
          <span class='prev'>
      <a href='#' class="pagination__prev">prev</a>
    </span>
          <span class='next'>
      <a href='#'class="pagination__next">next</a>          </span> 
        </p>
      </div>
    </div>