データ属性で表示する記事を絞り込む

NO IMAGE

データ属性で、一覧の記事を絞り込むサンプルです。属性を選ぶボタン(category-btn)と絞り込まれる要素(flex-one)の一覧になっています。is-animateクラスは、自分で作成したクラスです。若干不要な記述が入っていますが・・・

  • キーワード
  • A
  • B
要素
要素
要素
.category-btn{ list-style:none; display:flex; margin:40px 0; } .category-btn li{ margin-right:10px; } .category-btn li a{ display:inline-block; padding:2px 10px; border:1px solid #09315f; } .category-btn li a.is-select{ background:#09315f; color:#FFF; } .category-list .flex-one{ position: relative; } .category-list .flex-one a.boxlink{ position: absolute; width: 100%; height: 100%; display:block; top:0; left: 0; text-indent: 100%; /*テキスト非表示*/ white-space: nowrap; /*テキスト非表示*/ overflow: hidden; /*テキスト非表示*/ z-index:10; } .category-list:before{ content:””; display:block; width: 24%; height:0; order:1; } .category-list:after{ content:””; display:block; width: 24%; height:0; } .is-animate { opacity: 1; animation: .6s zoom-in; } @keyframes zoom-in { 0% { opacity: 0.3; transform: scale(.8); } 100% { opacity: 1; transform: none; } } @media(max-width:39em){ .category-btn{ display:block; } .category-btn li a{ display:block; margin:5px 0; } }

これをjQueryを使って絞り込みます。

var $btn = $('.category-btn [data-filter]'),
       $list = $('.category-list [data-category]');
   
$(window).on('load',function(){
    $list.hide().filter('[data-category = "kanto"]').show().addClass('is-animate');
});
	
$btn.on('click', function() {
     var $btnCat = $(this).attr('data-filter');
     $list.removeClass('is-animate');
	$btn.removeClass('is-select');
     if ($btnCat == 'all') {
       $list.show().addClass('is-animate');
		 $(this).addClass('is-select');
     } else {
        $list.hide().removeClass('is-animate').filter('[data-category *= "' + $btnCat + '"]').show().addClass('is-animate');
		 $(this).addClass('is-select');
     }
     return false;
   });