mwnz
mwnz

Reputation: 3

jQuery to hide certain types of list items

I have a little image gallery thing holding a bunch of different types of images.

I'd like to have options to show/hide different types of images, as well as an option to display all types. What would be the best way to do this?

This is the HTML for it.

<div id="categories">
  <a id="category_all" href="#all"><img src="all.png" /></a>
  <a id="category_type1" href="#type1"><img src="type1.png" /></a>
  <a id="category_type2" href="#type2"><img src="type2.png" /></a>
</div>
<div id="list">
  <ul class="images">
    <li class="class1"><img src="image.jpg"/></li>
    <li class="class2"><img src="image.jpg"/></li>
    <li class="class2"><img src="image.jpg"/></li>
    <li class="class1"><img src="image.jpg"/></li>
    <li class="class2"><img src="image.jpg"/></li>
    <li class="class1"><img src="image.jpg"/></li>
    <li class="class1"><img src="image.jpg"/></li>
    <li class="class1"><img src="image.jpg"/></li>
    <li class="class1"><img src="image.jpg"/></li>
    <li class="class1"><img src="image.jpg"/></li>
    <li class="class1"><img src="image.jpg"/></li>
  </ul>
</div>

I was thinking it would make sense to append seperate 'show'/'hide' classes with display:block and display:none but not sure how I should go about this as I'm new to jQuery.

Thanks

Upvotes: 0

Views: 2101

Answers (2)

sje397
sje397

Reputation: 41832

$('#category_all').click(function() {
  $('.class1,.class2').show();
});

$('#category_type1').click(function() {
  $('.class1').show();
  $('.class2').hide();
});

$('#category_type2').click(function() {
  $('.class2').show();
  $('.class1').hide();
});

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630469

You can do this pretty cleanly with a data-attribute, like this:

<div id="categories">
  <a data-show="*" href="#"><img src="all.png" /></a>
  <a data-show=".class1" href="#"><img src="type1.png" /></a>
  <a data-show=".class2" href="#"><img src="type2.png" /></a>
</div>

Then use that in a click handler, for example:

$("#categories a").click(function(e) {
  $("#list .images li").hide().filter($(this).data("show")).show();      
  e.preventDefault(); //prevent page scrolling to top
});

What this is doing is on click it's hiding all the <li> elements, then using .filter() the ones that match the selector in the data-show attribute...and showing those. When you want to add another type, just add a new link under categories and the matching selector with it, and you're all set.

Upvotes: 1

Related Questions