[ケーススタディ]simplePagination.jsを使ったページネーション実装
案件でページネーション実装する度に同じ事やってるっぽいので、コピペで済むようメモ。
今回使うJSライブラリ「simplePagination.js」の配布元は次のサイトとなる。
https://flaviusmatis.github.io/simplePagination.js/
記事リストが次のようなマークアップで定義される場合、
<div class="articles">
<dl>
<dt>タイトル</dt>
<dd>内容</dd>
</dl>
<dl>
<dt>タイトル2</dt>
<dd>内容</dd>
</dl>
...
<dl>
<dt>タイトルn</dt>
<dd>内容</dd>
</dl>
</div>
次のようなJSを組み込む。
$(function() {
let num__total_entries = $(".articles dl").length; //リストに表示する記事の総数.
let num__items_on_page = 12; //1ページ当たりの最大記事件数.
function paginationOnPageClick(currentPageNumber){
//ページ
$('.articles dl').hide();
$(".articles dl.page" + currentPageNumber ).show();
}
if ( num__total_entries > num__items_on_page ){
//リスト表示のトータル件数が、1ページ当たりの最大記事件数を超えたら、ページネーションを設ける。
$.when(
$('.articles').after('<ul class="pager"></ul>')
//ページネーションの枠作成.
)
.then(function(){
$(".articles dl").each(function(i){
$(this).addClass( "page" + Math.floor( i / num__items_on_page + 1 ) );
});
//リスト内の記事1件毎の要素に、ページ番号を示すclass値を付与する(例:page1).
$(".pager").pagination({
items: $(".articles dl").length,
itemsOnPage: num__items_on_page,
displayedPages: 3,
edges: 1,
ellipsePageSet: false,
prevText: '«',
nextText: '»',
onPageClick: function (currentPageNumber) {
paginationOnPageClick(currentPageNumber);
window.scrollTo({ //ページネーションのボタンが押されたら、ページの先頭までスクロールするようにする。
top: 0,
left: 0
});
}
})
paginationOnPageClick(1);
});
}
});
関連するタグ
関連するタグは現在ありません。