Search code examples
jquerytoggleclass

Jquery: One button click triggers all the buttons with same class


I have a code below which shows the hidden content of an article when the More Info button is clicked. When I click on one of the buttons, all buttons fire their event because they all have the same class. How can I show only the content where the More Info button is only clicked?

I got the code from this link, http://codepen.io/rossgray/pen/CpJgm

I'm still new to jquery, I really hope someone could help me on this. Thank you!

  var descMinHeight = 120;
  var desc = $('.desc');
  var descWrapper = $('.desc-wrapper');

  // show more button if desc too long
  if (desc.height() > descWrapper.height()) {
    $('.more-info').show();
  }


      // When clicking more/less button
      $('.more-info').click(function() {


    var fullHeight = $('.desc').height();

    if ($(this).hasClass('expand')) {
      // contract
      $('.desc-wrapper').animate({'height': descMinHeight}, 'slow');
    }
    else {
      // expand 
      $('.desc-wrapper').css({'height': descMinHeight, 'max-height': 'none'}).animate({'height': fullHeight}, 'slow');
    }

    $(this).toggleClass('expand');
    return false;

  });

Solution

  • Below instead of using class $('.desc-wrapper') to select all element with that particular class, only previous element $(this).prev() is selected. Updated

      $('.more-info').click(function() {
    
        var fullHeight = $('.desc').height();
    
      if ($(this).hasClass('expand')) {
    
      // contract
         $(this).prev().animate({'height': descMinHeight}, 'slow');
      }
      else {
      // expand 
         $(this).prev().css({'height': descMinHeight, 'max-height': 'none'}).animate({'height': fullHeight}, 'slow');
      }
    
       $(this).toggleClass('expand');
       return false;
     });