Search code examples
jqueryjquery-selectorsclickelementslidetoggle

jQuery button to show/hide multiple divs with same id


I have many products being populated dynamically, all with same id and class names. I want each "Buy Now" button to have its own div that toggles with click of button.

I do have the ability to assign an incrementing number index to the ids and classes, however, if there's a way to avoid it, I don't want to manually list each unique id and class to target each click function.

What's the best way to accomplish this?

Here's what I have now...

HTML:

 <button class="btn button-success clickme">Buy Now</button>
 <div class="book" style="display: none;">
     <!-- content here -->
 </div>

 <button class="btn button-success clickme">Buy Now</button>
 <div class="book" style="display: none;">
     <!-- content here -->
 </div>

jQuery:

$( ".clickme" ).click(function() {
  $( ".book" ).slideToggle( "slow", function() {
    // Animation complete.
  });
});

Solution

  • Ignoring thoughts surrounding using the same ID for multiple elements on the same page you have access to this in your function to show the book div.

    Example switching from using #clickme to attach the click event listener to .button-success:

    HTML

    <button class="btn button-success" id="clickme">Buy Now</button>
     <div class="book" style="display: none;">
         content
     </div>
    
     <button class="btn button-success" id="clickme">Buy Now</button>
     <div class="book" style="display: none;">
         content
     </div>
    
     <button class="btn button-success" id="clickme">Buy Now</button>
     <div class="book" style="display: none;">
         Content here
     </div>
    
     <button class="btn button-success" id="clickme">Buy Now</button>
     <div class="book" style="display: none;">
         content
     </div>
    

    JQUERY

    $( ".button-success" ).click(function() {
        $(this).next(".book").slideToggle( "slow", function() {
        // Animation complete.
      });
    });
    

    What this is doing:

    When a user clicks on any .button-success it looks for the next .book div and toggles the content.

    demo: http://jsfiddle.net/9zaLtmaf/