読み込んだincファイルの要素を絞込表示するjQuery – incboxfilter.js
概要
- 読み込んだincファイルの要素を付与されたクラス名を元に絞込表示する。
改造元
以下のエントリーを元に改造させていただきました。
成果物
http://hi3103.net/study/incboxfilter/
HTML
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="css/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="js/incboxfilter.js" charset="UTF-8"></script> <title>incboxfilter.js</title> </head> <body> <div class="filter"> <a class="all active" data-filter="all" href="#" role="button">Show All</a> <a class="green" data-filter="green" href="#" role="button">Show Green Boxes</a> <a class="blue" data-filter="blue" href="#" role="button">Show Blue Boxes</a> <a class="red" data-filter="red" href="#" role="button">Show Red Boxes</a> <a class="hoge" data-filter="hoge" href="#" role="button">Show Hoge Boxes</a> </div> <div class="boxes"></div> </body> </html>
box.inc
<a class="red" href="#">Box1</a> <a class="green" href="#">Box2</a> <a class="blue hoge" href="#">Box3</a> <a class="green" href="#">Box4</a> <a class="red" href="#">Box5</a> <a class="green" href="#">Box6</a> <a class="blue" href="#">Box7</a> <a class="red hoge" href="#">Box8</a> <a class="green" href="#">Box9</a> <a class="blue" href="#">Box10</a> <a class="red" href="#">Box11</a> <a class="green hoge" href="#">Box12</a> <a class="blue hoge" href="#">Box13</a> <a class="green" href="#">Box14</a> <a class="red" href="#">Box15</a> <a class="blue" href="#">Box16</a>
incboxfilter.js
$(function(){ $(".boxes").load("inc/box.inc", null, function() { var $filters = $('.filter [data-filter]'); var $boxes = $('.boxes a'); $filters.on('click', function(e) { e.preventDefault(); var $this = $(this); $filters.removeClass('active'); $this.addClass('active'); var $filterColor = $this.attr('data-filter'); if ($filterColor == 'all') { $boxes.fadeOut().promise().done(function() { $boxes.fadeIn(); }); } else { $boxes.fadeOut().promise().done(function() { $boxes.filter('.'+$filterColor).fadeIn(); }); } }); }); });
style.css
@charset "UTF-8"; *{ margin: 0; padding: 0; box-sizing: border-box; } html{ font:18px/3 Arial,sans-serif; text-align: center; } a{ text-decoration: none; display: block; color: #333; } /* filter */ .filter{ margin: 2em 30%; } .filter a{ display: block; position: relative; margin-bottom: 1em; } .filter a.active:before{ content: ''; position: absolute; left: 0; top: 0; width: 0; height: 0; border-style: solid; border-width: 15px 15px 0 0; border-color: #333 transparent transparent transparent; } /* boxes*/ .boxes{ display: flex; flex-wrap: wrap; } .boxes a{ width: 23%; margin: 0 1% 1em 1%; } .all{ background: lightgray; } .green{ background: lightgreen; } .blue{ background: lightblue; } .red{ background: lightcoral; } .hoge{ border: 1px solid #333; }