Ionică Bizău Ionică Bizău - 5 months ago 61
Javascript Question

How to correctly append dynamic GetUIKit accordions?

I'm trying to dynamically append UIKit Accordions into a sortable list. The initial items (accordions) are working, but the dynamically appended is not working.

HTML



<div class="second-list" data-uk-observe>
<div class="uk-sortable uk-margin uk-accordion" data-uk-sortable="{group:'test'}" data-uk-accordion="{showfirst: false}">
<div class="uk-margin">
<div class="uk-panel uk-panel-box uk-accordion-title">Item 1
<button class="uk-button delete-btn">&times;</button>
</div>
<div class="uk-accordion-content">test1</div>
</div>
<div class="uk-margin">
<div class="uk-panel uk-panel-box uk-accordion-title">Item 2
<button class="uk-button delete-btn">&times;</button>
</div>
<div class="uk-accordion-content">test2</div>
</div>
</div>
</div>


JavaScript



// Remove item handler
$(".delete-btn").on("click", function () {
// 400 is default
$(this).closest(".uk-margin").fadeOut(400, function () {
$(this).remove();
});
return false;
});

function addItem () {
var $container = $(".second-list").find("[data-uk-sortable]");
$container.append(
`<div class="uk-margin">
<div class="uk-panel uk-panel-box uk-accordion-title">new item
<button class="uk-button delete-btn">&times;</button>
</div>
<div class="uk-accordion-content">description</div>
</div>`
);
}

addItem();


This is the minimal example I created to reproduce the problem. The sortable dynamic item is working fine (can be dragged), but the accordion doesn't. When clicking it, I'm getting:

Uncaught TypeError: Cannot read property 'data' of undefined


What I have tried:


  • Using
    data-uk-observe
    in the sortable element. I don't feel any difference using it.

  • Trying to initialize the accordion using the UIKit API:

    UIkit.accordion($(".uk-margin"));
    UIkit.accordion($(".uk-accordion-title"));
    UIkit.accordion($(".uk-accordion-content"));


    None of these doesn't fixe the problem.



So, how to correctly append dynamic GetUIKit accordions?

JSFIDDLE

Answer

It looks like what you want to do is:

  • Omit the data-uk-accordion attribute.
  • Save the object returned from calling UIkit.accordion(element, options).
  • After new accordion child elements have been added, call accordion.update(). (assuming you saved the returned object above in a variable called accordion)

For more information about how I arrived at that, check out the related issue on GitHub.

(also posted as an answer on UIKit accordion and ng-repeat doesn't work)

Comments