Reputation:
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?
Upvotes: 2
Views: 67
Reputation: 12038
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>
Upvotes: 3