Monday, 27 May 2013

JQuery: Toggle display of a div

Javascript:

// show 'more-attributes' for ad if user clicks 'Show attributes' link
$('.show-hide-attributes').live('click', function () {
var $this = $(this);
$(this).closest('.meta-attrbt').find('.more-attributes').slideToggle(0,
function () {
$this.text($(this).is(':visible') ? "Hide attributes" :
"Show attributes");
});

return false;
});


HTML

<dd class="p-ads-dd meta-attrbt">
<a class="show-hide-attributes" href="#">Show attributes</a>
<div style="display: none;" class="more-attributes">
<p>Attribute 1: This is a detail</p>
<p>Attribute 2: This is another detail</p>
<p>Areas of expertise: Expertise 1</p>
<p>Areas of expertise: Expertise 2</p>
</div>

</dd>


JSFiddle:

http://jsfiddle.net/25QC7/



Attach function to click event of .show-hide-attributes

We are using classes ('more-attributes', 'show-hide-attributes)
because there are multiple instances of these on the page.

We are using .find() to attach the slideToggle() because there are
multiple rows containing these attributes. Each set of attributes is
specific to a single record.

Added function to slideToggle() so that label changes from 'Show
attributes' if attribute div is hidden, to 'Hide attributes' if the
div is displayed.

No comments: