I am using ajax to add / delete elements on page. When element is added / deleted then alert widget is displayed. I am using data-mage-init attribute to trigger js when element is clicked. When adding new element with jquery how I can generate it with data-mage-init attribute?
1 ) When element is created in template then data-mage-init attribute is not visible on page and it works. (Js is triggered when ‘a’ element is clicked).
Template:
<div class="item">
<div class="item-content">
<div class="name"><?= $product['name']; ?></div>
<div class="sku"><?= $product['sku']; ?></div>
<div class="remove-action">
<a
data-mage-init='{"learningPath": <?= json_encode(['removeUrl' => $block->getUrl('corporate/learning/removeCourse'), 'productId' => $product['id']]) ?>}'
href="#" class="action secondary"><?= __('Remove'); ?></a>
</div>
</div>
Browser:
..but when I generate that element with js then data-mage-init attribute is visible and its not working. Here is my code:
Js file:
$('.path-builder-selection .selection-container').append("<div class='item'><div class='item-content'>" +
"<div class='name'>n" + data['product']['name'] + "</div>" +
"<div class='sku'>"+ data['product']['sku'] + "</div>" +
"<div class='remove-action'><a data-mage-init='{"learningPath":{"removeUrl": " + data['remove_url'] + ", "productId": " + data['product']['id'] + "}}' href='#' class='action secondary'>" + data['remove_label'] + "</a></div>n" +
"</div></div>");
Browser:
Conclusion: data-mage-init attribute is not parsed when I create new element with it through js. Is there any way how I can add element through js/jquery and add data-mage-init attribute to it. (To be possible to delete that element later if needed again with js, otherwise I cannot delete element because data-mage-init is not parsed and js is not triggered)
2
Answers
Execute data-mage-init and x-magento-init in dynamic content
To trigger
.trigger('contentUpdated')
on the element when dynamic content is injected, use:This is an old question but maybe it helps to someone else:
Add as an attribute the data-mage-init, let say you want to add a menu:
This way you can initialize your element.