0

I created jQuery sorter plugin like below to filter by classes. But now I am not sure how to only display class="apple" by default. Right now when I reload the page both APPLE and TREE is visible.

<ul>
  <li class="apple">APPLE</li>
  <li class="tree">TREE</li>
  <li class="apple tree">ALL</li>
</ul>

<div>
  <div class="apple">APPLE</div>
  <div class="tree">TREE</div>
  <div class="apple">APPLE</div>
  <div class="tree">TREE</div>
  <div class="apple">APPLE</div>
  <div class="tree">TREE</div>
</div>

<script src="/js/jquery.min.js"></script>
<script type="text/javascript">
$("ul li").click(function() {
  visibleClasses = $(this).attr("class").split(" ");
  $("div div").hide(); // or slideUp / fadeOut
  for(i in visibleClasses) {
    $("div div."+visibleClasses[i]).fadeIn(500); // or slideDown / show
  }
});
</script>
Maca
  • 1,659
  • 3
  • 18
  • 42
  • 1
    FYI, it's not a safe practice to iterate an array with `for(i in visibleClasses)` both because `i` is an implicit global variable and because you shouldn't use `for(x in y)` to iterate arrays (because it also iterates properties). You should do it like this: `for (var i = 0; i < visibleClasses.length; i++)` and you should use `var` on your local variables so they aren't implicit globals. – jfriend00 Jan 17 '12 at 00:03

2 Answers2

2

Hide all non-apples with:

$("div div:not(.apple)").hide();

Rather than iterate the array, construct a selector that get's all the elements at once:

var selector = "div div." + visibleClasses.join(",div div.");

selector will contain "div div.apple,div div.tree" which will select elements that match either of the comma separated selectors. You can then do:

$(selector).fadeIn(500);

Edit: So, with this change, your code would look like this:

<script type="text/javascript">  
    $(function () {
        $("div div:not(.apple)").hide();
        $("ul li").click(function() {
            var visibleClasses = $(this).attr("class").split(" ");
            $("div div").hide();
            var selector = "div div." + visibleClasses.join(",div div.");
            $(selector).fadeIn(500);
        });
    });
</script>

By, the way, if you choose to iterate the Array use a regular for loop or Array.forEach(). Do not use for..in to iterate an Array. The for..in statement is for enumerating, not iterating.

Community
  • 1
  • 1
gilly3
  • 87,962
  • 25
  • 144
  • 176
  • Thank you for the tip but I am new to javascript and still learning. How would I implement this in my code? – Maca Jan 17 '12 at 01:52
1

Add this to the end of your script:

$("div div").hide();
$("div div.apple").show();
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112