jQueryプラグインIsotopeの使い方(フィルター、ソート)

jQuery

jQueryプラグインIsotopeの使い方を紹介します。

jQueryプラグインIsotopeの使い方

公式サイト:https://isotope.metafizzy.co/

jQueryのダウンロード

IsotopeはjQueryのプラグインのため、jQueryを使えるようにしておきます。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

isotope.pkgd.min.jsファイルのダウンロード

Download isotope.pkgd.min.jsというボタンがあるのでそれをクリックするとminファイルのコードが確認できます。
それをコピーして、isotope.jsなどとしてファイルを作成し、プロジェクトのフォルダに配置します。

html

<section class="portfolio" id="portfolio">
  <div class="portfolio__container">
    <h2 class="heading-secondary">Portfolio</h2>
    <div class="portfolio__buttons isotope-filter">
      <button class="button small" data-filter="*">All</button>
      <button class="button small" data-filter=".web-design">Web Design</button>
      <button class="button small" data-filter=".graphics-design">Graphics Design</button>
      <button class="button small" data-filter=".brand">Brand</button>
    </div>
    <div class="portfolio__images">
      <img src="../dist/img/portfolio-1.jpg" alt="" class="portfolio__image brand">
      <img src="../dist/img/portfolio-2.jpg" alt="" class="portfolio__image web-design">
      <img src="../dist/img/portfolio-3.jpg" alt="" class="portfolio__image graphics-design">
      <img src="../dist/img/portfolio-4.jpg" alt="" class="portfolio__image brand">
      <img src="../dist/img/portfolio-5.jpg" alt="" class="portfolio__image web-design">
      <img src="../dist/img/portfolio-6.jpg" alt="" class="portfolio__image brand">
    </div>
  </div>
</section>

クラス名はjsで指定すればいいので、なんでもかまいません。
上の場合だと、isotope-filterというのが、buttonのコンテナにあたります。
そのボタンには、data-filterという属性を付与して、そのプロパティにクラス名を書きます。すべての場合は、アスタリスク(*)を書きます。

注意点としては、data-filter属性の値は、クラスを表すピリオド(.)を忘れずに記載しましょう。

portfolio__imagesクラスというのが、フィルター対象となる画像のコンテナになります。
そして、portfolio__imageというのが、フィルターされるアイテムになります。
フィルターされるアイテムには、button要素のdata-filter属性で指定した値をクラス名として記述します。

jsファイル

var $grid = $('.portfolio__images').isotope({
  // options
  itemSelector: '.portfolio__image',
  // layoutMode: 'fitRows'
});

// filter items on button click
$('.isotope-filter button').on( 'click', function() {
  var filterValue = $(this).attr('data-filter');
  $grid.isotope({ filter: filterValue });
});

フィルターの対象となるアイテムの親要素となるクラス名を指定し、それにisotope({})をつなげます。
itemSelectorに指定するクラスが、フィルターされるアイテムになります。

下部では、フィルターをするときのボタン要素を指定します。上の場合だと、.isotope-filterクラスの中のbutton要素となります。
それがクリックされたら、data-filter属性の値として指定されているものと一致するものでフィルターできます。

jQuery

Posted by devsakaso