Toggling displaying children using jquery

When the "Album 1" link is clicked I want to toggle between hiding and showing the photos. However, right now it's not doing anything at all. I tried to debug it in console, but it's not outputting anything useful.

script.js

$(document).ready(function() {
    // album click toggle
    $('.album a').click(function() {
        console.log($(this).parent().find(".photos"));
        $(this).parent().find(".photo").hide();
    });
});

index.html

<div class="album">
            <h2><a href="#">Album 1</a></h2>
            <ul class="photos">
                <li>
                    <img src="img/img1.jpg">
                    <span class="info"><span>Image 1</span></span>
                </li>
                <li>
                    <img src="img/img2.jpg">
                    <span class="info"><span>Image 2</span></span>
                </li>
                <li>
                    <img src="img/img3.jpg">
                    <span class="info"><span>Image 3</span></span>
                </li>
            </ul>
        </div>

Answers 1

  • You're targeting .photo instead of .photos.

    Beside that you could actually Toggle like:

    jQuery(function($) {
    
      // album click toggle
      $('.album a').click(function(e) {
        e.preventDefault(); // Prevent browser scroll to top
        $(this).closest(".album").find(".photos").stop().slideToggle();
      });
      
      
    });
    *{margin:0; box-sizing:border-box;}
    
    .album ul  {display:none; list-style:none; padding:0; margin:0; overflow:auto;}
    .album li  {display:inline-block; vertical-align:top;}
    .album li>*{display:block;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="album">
      <h2><a href="#">Album 1</a></h2>
      <ul class="photos">
        <li>
          <img src="//placehold.it/64x50">
          <span class="info"><span>Image 1</span></span>
        </li>
        <li>
          <img src="//placehold.it/64x50">
          <span class="info"><span>Image 2</span></span>
        </li>
        <li>
          <img src="//placehold.it/64x50">
          <span class="info"><span>Image 3</span></span>
        </li>
      </ul>
    </div>
    
    <div class="album">
      <h2><a href="#">Album 2</a></h2>
      <ul class="photos">
        <li>
          <img src="//placehold.it/64x50">
          <span class="info"><span>Image 1</span></span>
        </li>
        <li>
          <img src="//placehold.it/64x50">
          <span class="info"><span>Image 2</span></span>
        </li>
        <li>
          <img src="//placehold.it/64x50">
          <span class="info"><span>Image 3</span></span>
        </li>
      </ul>
    </div>


Related Articles