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>
1
  • 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. Commented Jan 17, 2012 at 0:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the tip but I am new to javascript and still learning. How would I implement this in my code?
1

Add this to the end of your script:

$("div div").hide();
$("div div.apple").show();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.