2

I want to make a very simple buttons to switch pages ("next" and "previous"). I've got my page paginated like that.

function showPages(id = 1) {
  var totalNumberOfPages = 6;
  for (var i = 1; i <= totalNumberOfPages; i++) {
    if (document.getElementById('page' + i)) {
      document.getElementById('page' + i).style.display = 'none';
    }
  }
  if (document.getElementById('page' + id)) {
    document.getElementById('page' + id).style.display = 'block';
  }
};

showPages();
<span style="float: left;">
  <a href="#" onclick="javascript:showPages(id--)">Previous</a>
</span>

<span style="float: right;">
  <a href="#" onclick="javascript:showPages(id++)">Next</a>
</span>

When I click on "next" or "previous" button, it behave strangely. Sometimes it goes to the next page, sometimes it doesn't...

(sub-question: How can I do to restrain the code so it doesn't try to display a -1 page or a page number above the maximum number of page?

1
  • if (element exists) hide it if(element exists) show it..... Commented Sep 18, 2018 at 18:03

1 Answer 1

3

Do not use id-- or id++ in your links because this is modifying the actual page id. Instead use +1 or -1 like this:

<span style="float: left;">
    <a href="#" onclick="javascript:showPages(id - 1)">Previous</a>
</span>

<span style="float: right;">
    <a href="#" onclick="javascript:showPages(id + 1)">Next</a>
</span>
Sign up to request clarification or add additional context in comments.

3 Comments

It's not working, unfortunately. id - 1 links to a non-existing page "page-1" and "id + 1" to "page+1", but not the "actual page" + 1 page. I mean, it doesn't increment the number of the page being viewed :/
You'll have to update your logic to consider the problem of being on the first or last page and not adding the link in that situation.
I guess the problem is that I use anchors. I believe this is why no data are stored in "id", nor incremented. I'm actually looking for a way to solve that problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.