1

In trying to create a dynamic accordion with jquery, I can't figure out why the individual elements aren't collapsed. They just appear as text rather than taking on the accordion effect. Can anyone spot my mistake? (Assume that the data variables all contain data)

edit: I just tried it in firefox instead of chrome for curiosity's sake and the accordion behavior works..I don't get it

var outdiv = $('<div data-role="collapsible-set"></div>');

for(var i=0; i<data.length; i++){

    var innerdiv = $('<div data-role="collapsible" data-collapsed="true" ></div>');
    innerdiv.append('<h3>' + 'Tweet #' + i + '</h3>');
    innerdiv.append('<p>' + data[i].text + '</p>');

    outdiv.append(innerdiv);

    outdiv.appendTo('#output');


}
Sam
  • 2,309
  • 9
  • 38
  • 53

4 Answers4

3

You need to call collapsibleset() method on your outdiv

$('#output [data-role=collapsible-set]').collapsibleset();

Working jsFiddle here

peterm
  • 91,357
  • 15
  • 148
  • 157
  • great answer! Could you briefly explain why that's needed instead of the trigger? – Sam Mar 22 '13 at 03:15
  • They both work in jqm 1.2 and 1.3. `collapsibleset()` directly calls widget initialization method, `trigger('create')` triggers a `create` event but you need to use it **on a parent element** and it's good when you need to enhance more than one widget at a time. – peterm Mar 22 '13 at 03:42
0

I'm not a jQuery mobile user but it looks to me like you need to set up the behaviours for your added content, something like $('#output').trigger('create') after your loop.

Its discussed more here

Community
  • 1
  • 1
kevmc
  • 1,284
  • 7
  • 8
0

I don't know if you can select a whole element this way or not, but you can also use jQuery's Attribute Contains Selector

//So your outdiv would become 
var outdiv = $('div[data-role*="collapsible-set"]');

//And then innerdiv, something like
var innerdiv = $('div[data-role*="collapsible"][data-collapsed*="true"]');
SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59
0

Change your code to:

outdiv.append(innerdiv).collapsibleset("refresh");

You will have to download jQuery Mobile ver 1.3.2.

user13500
  • 3,817
  • 2
  • 26
  • 33