I am using ajax to insert a series of informational blocks via a loop. The blocks each have a title, and long description in them that is hidden by default. They function like an accordion, only showing one description at a time amongst all of the blocks.
The problem is opening the description on the first block. I would REALLY like to do it with
javascript right after the loop that is creating them is done. Is it possible to manipulate
elements created ofter an ajax call without using the callback?
<!-- example code-->
<style>
.placeholder, .long_description{
display:none;}
</style>
</head><body>
<script> /* yes, this script is in the body, dont know if it matters */
$(document).ready(function() {
$(".placeholder").each(function(){ // Use the divs to get the blocks
var blockname = $(this).html(); // the contents if the div is the ID for the ajax POST
$.post("/service_app/dyn_block",'form='+blockname, function(data){
var divname = '#div_' + blockname;
$(divname).after(data);
$(this).setupAccrdFnctly(); //not the actual code
});
});
/* THIS LINE IS THE PROBLEM LINE, is it possible to reference the code ajax inserted */
/* Display the long description in the first dyn_block */
$(".dyn_block").first().find(".long_description").addClass('active').slideDown('fast');
});
</script>
<!-- These lines are generated by PHP -->
<!-- It is POSSIBLE to display the dyn_blocks -->
<!-- here but I would really rather not -->
<div id="div_servicetype" class="placeholder">servicetype</div>
<div id="div_custtype" class="placeholder">custtype</div>
<div id="div_custinfo" class="placeholder">custinfo</div>
<div id="div_businfo" class="placeholder">businfo</div>
</body>
The problem is that as AJAX is asynchronus (by default)
will execute before there is any data. So you cannot avoid callbacks.
Instead of polling you could define the following function
If you want to slideDown the first one when all the processing is done.
So the script would look like this
EDIT: Regarding you comment about not knowing wether it matters or not to have your javascript on the HTML, check this SO question
As Nick suggested there is a better way to achieve the same thing (instead of using the
ajaxDonefunction)