Reputation: 23
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;
});
Upvotes: 1
Views: 1046
Reputation: 2869
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;
});
Upvotes: 1
Reputation: 1003
That is how jquery works.
If you attach an event to the "more-info" class, all of the objects having this class will fire the event.
If you only want one object to fire the event, then specify an unique id to this object (for example, id="id1") and then in the jquery object attach the click event only to the "id1" identified object, i.e.
$('#id1').click(function() {
...
}
Upvotes: 0