Dynamically adding collapsible elements
Source: http://jquerymobile.com/demos/1.0a2/#docs/content/content-collapsible.html When I add an element like this manually to my code, it is displayed properly. But when I try to add it with jQuery like this:
$('body').append('<div data-role="collapsible"><h3>Title</h3><p>Content</p></div>');
It just displays title in h3 and the content below it, so not as a collapsible element. How can I fix this?
Solution 1:
The easiest way to achieve this is to call the collapsible() method on the dynamically created divs:
$('div[data-role=collapsible]').collapsible();
source : http://forum.jquery.com/topic/dynamically-add-collapsible-div
Solution 2:
this is what i do. Hope it helps
HTML
<div id="collapsibleSet" data-role="collapsible-set">
<div id="ranking1"></div>
</div>
Javascript
$('#ranking1').replaceWith('<div id="ranking1" data-role="collapsible" data-collapsed="false">' + htmlRankings(ranking) + '</div>');
$('#collapsibleSet').find('div[data-role=collapsible]').collapsible({refresh:true});
htmlRankings() is a js function that returns some html that i want inside the collapsible div. it can be something like this
<h3>11</h3>
<span>test</span>
Solution 3:
I think
after setting the innerhtml, simply tiggerring a event on it should render the dynamic contnet like below
$('#<divId or elementId').trigger("create");
Solution 4:
This code is for perl, you can modify it for any programming language.
<a href="javascript:collapsible('$div_instance','$imageID')">
<IMG id='$imageID' SRC='$imagePath' alt='(Expand / Collaspe Section' title='Expand / Collaspe' width=10 height=10>
$display_header <br/></a>
<div id=$div_instance name=$div_instance
style="overflow:hidden;display:$display_option;margin-left:30px; margin-top:20px;">
<-- your content -->
</div>
<script language="JavaScript" type="text/javascript">
<!--
function collapsible(theID,imageID) {
var elemnt = document.getElementById(theID);
var imageObject =document.getElementById(imageID);
if(elemnt.style.display == 'block') {
elemnt.style.display ='none';
imageObject.src='images/expand_icon.gif';
}
else{
elemnt.style.display ='block';
imageObject.src='images/expand_icon_down.gif';
}
}
// -->
</script>
REF: http://www.ssiddique.info/simple-javascript-to-create-dynamic-collapsible-section.html
Solution 5:
As of jquery mobile beta2 you trigger an event - .trigger('create')