I just started out with jQuery and really only need it for some very basic stuff. Here’s what I’m trying to do:
I separate content into an “.overview” div and a “.detail” div. jQuery looks through all the “.detail”-divs, moves up one element (.prev(“.overview”)) and appends a button. Then it scales down all the “.detail” divs to zero, and uses the buttons to reveal/hide them respectively.
I had first hard-coded the buttons, but it seemed tedious and unnecessary. But as soon as I generate them dynamically, the reveal/hide function does not work anymore. I searched around, but I might not be using the right terms…
Here’s my html:
<div class="title">
<h2>Title</h2>
</div>
<div class="overview">
<p>...</p>
</div>
<div class="detail">
<p>...</p>
</div>
And this is the jQuery code (in a separate file):
$(document).ready(function() {
$(".detail").each(function() {
$(this).prev("div").append("<div class=\"expand\"><a href=#>more</a></div>");
$.data(this, "realHeight", $(this).height());
}).css({ overflow: "hidden", height: "0" });
$(".expand").toggle(function() {
$(this).html("<a href=#>less</a>")
var div = $(this).next(".detail")
div.animate({ height: div.data("realHeight")+21 }, 250);
}, function() {
$(this).html("<a href=#>more</a>")
$(this).next(".detail").animate({ height: 0 }, 250);
});
});
I would hugely appreciate if you could point me in the right direction. Or, if it’s a stupid one, just tell me what I need to do a search for. 🙂
Thanks!
$.next() get the next sibling and “.detail” is not a sibling of “.expand” in your DOM structure. You may want to get to the parent (“.overview”) and then get the next().
Or change the structure so that they are siblings.
EDIT:
In your code you do this, and that’s why they are not siblings:
Try this fiddle with “parent” working, using the base code in the question.
Here is another fiddle with the div “expand” inserted as sibling using
insertBefore. It works exactly the same and you don’t need the.parent()call.