Search code examples
javascriptphpslidetoggle

How can i activate and associate slideToggle function (with JavaScriot) only for the one part i'm trying to show in a foreach loop?


I wanna show the desc of a product whenever i click in the relative info but with my code everytime i click in a random info it shows me all the desc of all the products. Please help me.

      <script type="text/javascript">
            $(function () {
                  $("p.info").on('click', function () {
                  $("p.desc").slideToggle();
                });
          });
      </script>




     // the info and desc of the products are cointaned in:


     <div class="products_container">
            <ul>
                @foreach ($products as $product)
                    <li>
                        <div class="products">
                            @include('helpers/productImg', ['attrs' => 'imagefrm', 'imgFile' => 
      $product->image])
                            <p id="product_name"><strong>{{ $product->name }}</strong></p>
                            <p>{{ $product->descShort }}</p>
                            @include('helpers/productPrice')
                            <p class="info">Info prodotto</p>
                            <p style="display:none" class="desc">Descrizione: {!! $product->  
      `                     descLong !!}</p>
                        </div>
                    </li>
                @endforeach
            </ul>
            </div>

Solution

  • Well that's because you're using a class .desc that's why it's toggling all elements with that class. however could infer from your code that .desc is next to .info onclick event so instead of

      $("p.info").on('click', function () {
                  $("p.desc").slideToggle();
                });
    

    you should use

      $("p.info").on('click', function () {
                  $(this).next().slideToggle(); //element next to clicked p.info
                });