Simple pagination with jquery or javascript
Using jQuery:
<a href="#" id="prev">Prev page</a>
<a href="#" id="next">Next page</a>
<div class="pagination">
<div class="post" id="page1"> <!-- I gave every "page" an ID. -->
<h3> head1 </h3>
<p> Test1 </p>
</div>
<div class="post" id="page2">
<h3> head2 </h3>
<p> Test2 </p>
</div>
<div class="post" id="page3">
<h3> head3 </h3>
<p> Test3 </p>
</div>
<div class="post" id="page4">
<h3> head4 </h3>
<p> Test4 </p>
</div>
<div class="post" id="page5">
<h3> head5 </h3>
<p> Test5 </p>
</div>
<div class="post" id="page6">
<h3> head6 </h3>
<p> Test6 </p>
</div>
</div>
All you need to do in this situation is dynamically hide every page except the one you want to see:
function showPage(page) {
$('.pagination .post:not(#page'+page+')').hide();
$('.pagination .post#page'+page).show();
}
If you want next and previous buttons you can easily do so like this:
function prevPage() {
if (page == 1) {
page = $('.pagination .post').length;
} else {
page--;
}
showPage(page);
}
function nextPage() {
if (page == $('.pagination .post').length) {
page = 1;
} else {
page++;
}
showPage(page);
}
Just note that you need to store the number of the page (I used page
in the example) if you want to have next and previous buttons.
Michi
Updated on June 04, 2022Comments
-
Michi almost 2 years
I want to include a "pagination" with jquery or javascript to my website.
Therefore, I have created the following simple html-code:
<div class="post-list"> <div class="post"> <h3> head1 </h3> <p> Test1 </p> </div> <div class="post"> <h3> head2 </h3> <p> Test2 </p> </div> <div class="post"> <h3> head3 </h3> <p> Test3 </p> </div> <div class="post"> <h3> head4 </h3> <p> Test4 </p> </div> <div class="post"> <h3> head5 </h3> <p> Test5 </p> </div> <div class="post"> <h3> head6 </h3> <p> Test6 </p> </div> </div> <div class="pagination"> </div>
I am Newbie in web development and I don't know how to write a simple javascript or jquery code to make a pagination work. After searching the internet I haven't found any simple solution for it.
Therefore, I would really appreciate it if you could tell me a jquery or javascirpt code that I can apply to this html code.
Thanks for any help :-)
-
Michi almost 9 yearsHi xsquared, Thanks for your answer. It is working :-) However, I also want that the user can click on page number buttons like 1 2 3 4 in additon to the next and previous buttons. How can i do that?
-
danielrw7 almost 9 yearsYou can do this even easier than next and previous buttons. Updated fiddle. A link that will open a specific page will look like this:
<a href="#" onclick="showPage(1); return false;"></a>