2014/09/06

ブログとかのアーカイブの表示方法について考えてみた

長くなってきたブログのアーカイブをどう表示するか?

とりあえず「もっとみる」的なスクリプトを考えてみました。

こんな感じのhtmlで。

<aside id="archives">
 <h3 class="widget-title">Archives</h3>
 <ul>
  <li>2013/12</li>
  <li>2014/1</li>
  <li>2014/2</li>
  <li>2014/3</li>
  <li>2014/4</li>
  <li>2014/5</li>
  <li>2014/6</li>
  <li>2014/7</li>
  <li>2014/8</li>
  <li>2014/9</li>
 </ul>
</aside>

こんな感じのスクリプトを入れる(jQuery使用)

$(function() {
 var $target = $('#archives');
 var count = 1;
 var num = 5;//表示する数
 var l = $target.find('li').length;
 var style = 'display: block; margin: 0 auto; width: 25px; height: 25px; box-shadow: none; cursor: pointer';
 if(num < l) {
  $('#archives li:gt(' + (num - 1) + ')').css('display', 'none');
  $('').attr({ 'src': 'http://example.com/images/arrow.png', 'style': style })
   .appendTo($target)
   .bind('click', function() {
    $('#archives li:lt(' + (num * ++count) + ')').fadeIn(350);
    if(l <= num * count) $(this).remove();
   });
 }
});

もっと見る的なjavascriptがUX的にいけてないとの記事発見。

ページ遷移して、戻ったときに「もっと見る」で開いた部分が元に戻ってる。

確かに。読んで納得。

そんで少し訂正。タブを閉じるまで開いた分をキープ。

var num = 5;//表示する数
var isStorage = false;
try {
 if(typeof sessionStorage['moreCnt'] === 'undefined') sessionStorage['moreCnt'] = 1;
 isStorage = true;
 moreBtn(sessionStorage['moreCnt']);
} catch(e) {
 moreBtn();
}

function moreBtn(count) {
 count = count || 1;
 var $target = $('#archives');
 var l = $target.find('li').length;
 var style = 'display: block; margin: 0 auto; width: 25px; height: 25px; box-shadow: none; cursor: pointer';
 if(num * count < l) {
  $('#archives li:gt(' + (num * count - 1) + ')').css('display', 'none');
  $('').attr({ 'src': 'http://example.com/images/arrow.png', 'style': style })
   .appendTo($target)
   .bind('click', function() {
    $('#archives li:lt(' + (num * ++count) + ')').fadeIn(350);
    if(isStorage) sessionStorage['moreCnt'] = count;
    if(l <= num * count) $(this).remove();
   });
 }
};

なんかコードがすっきりしませんが、、、

一応DEMO



今後は小ネタを遠慮なく書いていこうと思います。