jQuery スクロールで記事の自動読み込みを実現する方法 – グリッドレイアウトにも対応 – infinititescroll等

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんばんは。今回のtipsは【jQuery スクロールで記事の自動読み込みを実現する方法 – グリッドレイアウトにも対応】についてです。自動読み込みと書きましたが、クリック等の手動も可能です。結構見かける手法ですのでメモしておきます。

自動読み込み用プラグイン【infinitescroll

インフィニティスクロール、このプラグインを使えば簡単に自動読み込みを実現してくれます。設置方法も簡単で非常に優秀なプラグインです。

スクロールで自動読み込み


<div id="blogBody">
<div class="post">….</div>
<div class="post">….</div>
<div class="post">….</div>
</div>
<div id="nav"><a class="next" href="page2.html">NEXT</a></div>


このHTMLは参考構成です。このような構文だった場合jsは以下のように設定します。

<script type="text/javascript">
$(function(){
$(‘#postBody’).infinitescroll({
navSelector : "div#nav",
nextSelector : "div#nav a#next",
itemSelector : "#postBody div.post"
});
});
</script>

ローディング画像の指定、全記事読み込み後のテキストの指定等

他にも色々な設定が有りますので、詳しくは本家サイトをご確認ください。


<script type="text/javascript">
$(function(){
$(‘#postBody’).infinitescroll({
navSelector : "div#nav",
nextSelector : "div#nav a#next",
itemSelector : "#postBody div.post"
loadingImg : "ローディング画像.jpg",
loadingText : "現在読み込み中です",
donetext : "全ての記事を読み込みました"
});
});
</script>

クリック等のアクションで読み込み

スクロールで自動読み込みさせたくない時は以下の設定をします。


<script type="text/javascript">
$(function(){
$(‘#postBody’).infinitescroll({
navSelector : "div#nav",
nextSelector : "div#nav a#next",
itemSelector : "#postBody div.post"
loadingImg : "ローディング画像.jpg",
loadingText : "現在読み込み中です",
donetext : "全ての記事を読み込みました"
});

$(window).unbind(‘.infscr’);
$(‘a#next’).click(function(){
$(document).trigger(‘retrieve.infscr’);
return false;
});

});
</script>

自動読み込み関連は以上になります。

自動読み込み用 + グリッドレイアウト

これは先ほどの【infinitescroll 】とグリッドレイアウト用のプラグイン【jQuery Masonry】を併用する事で実現できます。詳しくはMasonry、append後の操作のメソッドを参照してください。


<script type="text/javascript">
$(function(){
var $container = $(‘#postBody’);
$container.imagesLoaded(function(){
$container.masonry({
itemSelector: ‘#postBody div.post’,
columnWidth: 300
});
});
$container.infinitescroll({
navSelector : "div#nav",
nextSelector : "div#nav a#next",
itemSelector : "#postBody div.post"
loadingImg : "ローディング画像.jpg",
loadingText : "現在読み込み中です",
donetext : "全ての記事を読み込みました"
},function( newElements ) {
var $newElems = $( newElements );
$newElems.imagesLoaded(function(){
$container.masonry(‘appended’,$newElems,true);
});
});
});
</script>

Masonry demo

 
以上になります。個人的にはMasonryサイドのアニメーションをフェードのみにしたく、アニメーションをfalseに設定後、プラグインを以下のように改変して使用しています。


//before L336
appended : function( $content, isAnimatedFromBottom, callback ) {
if ( isAnimatedFromBottom ) {
this._filterFindBricks( $content ).css({ top: this.element.height()});
…..

//after
appended : function( $content, isAnimatedFromBottom, callback ) {
if ( isAnimatedFromBottom ) {
this._filterFindBricks( $content ).addClass(‘postafter’);
this._filterFindBricks( $content ).css({ top: this.element.height()});
this._filterFindBricks( $content ).animate({‘opacity’:’1′},500);
…..