I have this code to create div and collapse/expand element within each created div.
var i=1;
$('#addDiv').click(function() {
var divId="addedDiv"+i;
$(".content_body").slideUp(500);
$('<div></div>').attr({
'id' : divId,
'class' : 'addedDiv'
})
.appendTo('#container').load("content.php");
$(".content_head").click(function()
{
$(this).next(".content_body").slideToggle(600);
});
i++;
});
content.php :
<h2 class="content_head" style="background:orange;"> header</h2>
<div class="content_body" style="background:blue;"> content </div>
html :
<input id="addDiv" type="button" value="add div" >
<div id="container" style="width:500px;height:auto;background:red;"></div>
Say 5 div created, the expand/collapse on 1st,2nd and 3rd created div not working well.
How to fix this problem and also how to insert the ‘id’ of created div into header of each
(e.g. header of 2nd div = header addedDiv2) ?
Thanks in advance for any suggestions.
You are binding the click handler for
content_headbefore it actually gets loaded. To correct the issue, you need to bind the events after it gets loaded by binding the events inside the success callback ofload():