Reputation: 321
html:
<h3>PS elementum justo ligula</h3>
<div class="hide">elementum justo ligula, interdum scelerisque dui feugiat eget. Pellentesque at dignissim velit, eget volutpat lacus. Proin non metus eget quam efficitur maximus.
<button class="hide">Close</button>
</div>
<h3>Justo ligula</h3>
<div class="hide">Pellentesque at dignissim velit, eget volutpat lacus. Proin non metus eget quam efficitur maximus. Nulla blandit eros eu placerat rhoncus. Quisque in faucibus nibh. Cras ultrices iaculis purus porta.
<button class="hide">Close</button>
</div>
jquery:
$("div.hide").hide();
$("h3").click(function () {
$(this).next("div.hide").slideToggle("slow");
});
$("button.hide").click(function () {
$(this).parents("div.hide").slideToggle("slow");
});
i managed to get it work.: http://jsfiddle.net/qodgmhnd/
i just want you to check: is there more elegant solution?
and i need to add one more thing: close previouse content than next header is also clicked. right now it closes than parent header or close button is clicked.
Upvotes: 1
Views: 1653
Reputation: 82231
You can use single click handler to achieve this. also you can traverse to immediate parent using .parent()
with elements context:
$("button.hide,h3").click(function () {
var target = $(this).is('h3') ? $(this).next("div.hide") : $(this).parent();
target.slideToggle("slow");
});
Upvotes: 1