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

Real time search bar filter for photo gallery based off caption's content.

I'm still working on the search bar interactivity. I have the search bar set up and I would like to write a function in Javascript that will filter the photos based off what words are in the captions. Below is my HTML and JavaScript code. I have tried multiple codes to no avail. Can anyone point me in the right direction? Not asking for the complete answer, but maybe a few hints or tips that could help me get there. Thanks in advance! BTW, the 2nd code in the JavaScript screen shot is what I have right now. My previous one is above it.

/*****$search.keyup(function(event){
  var title = $('.imageGallery img').attr('data-title');
  if ( $title.toLowerCase() === $search.toLowerCase()) {
    $('imageGallery img').show();      
   } else {
    $('imageGallery img').hide();
   }
});
***/

$search.keyup(function(){
  var $title = $('.imageGallery img').attr('data-title').val();
  var $searchterm = $search.val();
  if ( $searchterm.toLowerCase() === $title.toLowerCase())
  {
      img.show();
  } else {
    img.hide();
  }
});
<form action="" method="post">
      <fieldset>
        <input type="search" id="filter" name="user_search" placeholder="Search(16pt)">
      </fieldset>
    </form>
    <ul class="imageGallery">
      <li><a href="img/fullsize/01.jpg" data-title="I love hay bales. Took this snap on a drive through the countryside past straw fields." data-lightbox="picture_one"><img src="img/thumb/01.jpg" alt=""></a></li> 

1 Answer

Steven Parker
Steven Parker
243,318 Points

Here's a few things I noticed offhand:

  • "$search" is not defined but is used to assign $searchterm
  • "img" is not defined
  • .val() is not a method of a value that would be returned by .attr()
  • the "data-title" attribute of the first "img" element is referenced, but that attribute is only used on the "a" element
  • the code uses jQuery, but it's not clear that jQuery is actually being loaded
  • a direct comparison of the strings will only be true if the strings match exactly (words, spaces, capitalization, etc)
  • the code will require some revision to be able to work on more than one list item
  • if multiple items are to be searched, a loop will probably be needed

I hope that helps! You've got a bit of work to do there.