Is there a way to get this working? I'm adding new list items dynamically to an expandable list, but they simply don't work.
You need to initialize that element after it was added dynamically
try to call $('.collapsible').collapsible(); after the element is added.
Do I need to apply it to the new li? Like $('.expandable').collapsible('li');?
I have no idea how the component is coded, and the following thinking might by too naive, but seems like an example of attaching an event handler to each li (potentially hundreds of event listeners attachments) instead of attaching it once to the parent, and setting the scope.
So instead of:
$('ul li').on('click', function() {
// do something
// but it won't work on dinamically added new items
});
it should be:
$('ul').on('click', 'li', function() {
// do something
// and it will also work on dinamically added new items
});
Is this the case?
No you don't need to, the argument of collapsible is to turn on / off the accordion
See the documentation about collapsible for more information:
http://materializecss.com/collapsible.html#intialization
Just try to call $('.collapsible').collapsible(); after the element was added dynamically.
Also, try to put an example on CodePen or JSFiddle
I still find a problem, the last item can't be clicked. I'm using Vuejs to handle the UI. Seems like it takes slightly more time to add a new item to the array and render the li onto the page than reinitializing the component.
I also encounter this problem before when adding dynamic view / html.
You could try to use setTimeout, or use promise if applicable to initialize it.
FYI, Some component even doesn't behave correctly / work if you initialize it 2 or more times (such as .button-collapse to activate the SideNav, or .modal-trigger).
That's why I suggest you to use exact selector before to prevent reinitializing the initialized elements (e.g: $(nav .add-dynamically-class .button-collapse').sideNav();), However in your case, the ul is the one of .collapsible, so i think my suggestion isn't applicable.
According to their documentation:
Collapsible elements only need initialization if they are added dynamically. You can also pass in options inside the initialization, however this can be done in the HTML markup as well.
I hope they gonna change this somehow in future version..
I managed to fix this one (no need to reinitialize). I'll try to make a PR, but I have a feeling that stuff like this happens throughout the whole library.
EDIT: PR'd it. #2281.
Fixed in e8ea639e2ef4cd4949d81becd0391039a65087a8
Thanks again for the PR johnRivs!
Most helpful comment
You need to initialize that element after it was added dynamically
try to call
$('.collapsible').collapsible();after the element is added.