Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Filtering images in a live search by caption

Hi! I am having trouble getting this code to run. This is for the Image Gallery project for the FEWD track. What I need to do is filter through the images by caption and hide any pictures whose caption does not match the text entered in the search bar. When the user opens the page, all images are displayed and a search box is above. If the user types "a", I want all photos with captions that DO NOT contain "a" to be hidden from the page. I'm not trying to do anything fancy with the first letter of the word right now. I am new to javascript and would appreciate any feedback!

JavaScript

var $captions = $(function(){
  $('img').each(function() {
    $(this).attr('title')
        });
});
var $photos = $(".gallery");

$("#filter").keyup(searchPics() {
 if ($(this).str.toLowerCase().indexOf($captions) < 0){
    $(this "img").hide();
  } else {
    $("img").show();
    }  
  });

HTML Example

 <form action="" method="post">
      <fieldset>
        <input type="text" id="filter" name="search" placeholder="Search(16pt)">
      </fieldset>
    </form>
    <ul class="photos">

      <li><a class="gallery" href="photos/fullsize/01.jpg"><img src="photos/01.jpg" alt="Hay Bales" title="I love hay bales. Took this snap on a drive through the countryside past some straw fields."></a></li>

     <li><a class="gallery" href="photos/fullsize/02.jpg"><img src="photos/02.jpg" alt="Lake" title="The lake was so calm today. We had a great view of the snow on the mountains from here."></a></li>

     <li><a class="gallery" href="photos/fullsize/03.jpg"><img src="photos/03.jpg" alt="Canyon" title="I hiked to the top of the mountain and got this picture of the canyon and trees below."></a></li>

1 Answer

Steven Parker
Steven Parker
243,318 Points

This snippet has a few issues that might need to be addressed:

  • where it has searchPics(), it seems like it should be function()
  • where it has $(this "img"), it seems like $("img") may have been intended
  • selecting all images at once to hide or show may not yield the desired functionality
  • the use of indexOf may also not yield the desired functionality
  • you might need a loop to iterate through the images and show or hide them individually