McPhelpsius McPhelpsius - 4 months ago 12
Javascript Question

Dynamically created collapsible-set in jQuery Mobile

Okay, once i see the answer to this, I will feel stupid. I'm certain of that.

I've created this exactly the way I want to before, but I am refactoring my code for a new version right now. I am trying to dynamically create collapsible sets in jQuery Mobile, but my html does not render right.



<div data-role="header">
<h2>Playground</h2>
</div>
<div data-role="content">
<div data-role="button" id="addprimary" data-inline="true">Add 5</div>
<div data-role="collapsible">
<h4>Collapsible</h4>
<form id="makecollapsible">
</form>
</div>
</div>
<div data-role="footer">
<h4>Please, no applause</h4>
</div>
</div>

<script>
$('#addprimary').on('click', function () {
Markup.Collapsible();
});

var Markup = new Object();


Markup.Collapsible = function () {

$('#makecollapsible')
.append($('<div>')
.attr({ 'data-role': 'collapsible-set', 'id': 'primary' })
);
for (i = 0; i < 5; i++) {
($('<div>')
.attr({ 'data-role': 'collapsible', 'data-content-theme': 'c',
'data-collapsed': 'true' })
.html('<h4>' + i +'</h4>'))
.appendTo('#primary');
}
}
</script>


Could somebody please take a look at this http://jsfiddle.net/c2jLY/ and tell me what I have wrong? My
<div>
s with
data-role='collapsible'
are not rendering as collapsibles, which is also having an effect on the HTML I am trying to put in them later on.

Help is appreciated, thanks!

Answer

Inside Markup.Collapsible function and at the end of it, add the below. For collapsible-set, you need to tell jQM that you're enhancing a .collapsibleset() and combine it with .trigger('create').

$('#makecollapsible').collapsibleset().trigger('create');

Demo


I forgot to mention that when appending items dynamically, call enhancement methods on parent element; doing so, will enhance children elements. Thus, you don't need to use .collapsible().trigger('create') for each collapsible appended.

Comments