How can I update/refresh Google MDL elements that I add to my page dynamically?
You can use the componentHandler.upgradeDom();
for dynamically upgrade the element or use the following lines for downgrade the existing element and upgrade it again
Type 1:
$(".data").find(".is-upgraded").each(function(){
$(this).removeAttr("data-upgraded").find(".mdl-switch__ripple-container,.mdl-switch__track").remove(); //downgrade the existing upgraded elements
});
componentHandler.upgradeDom(); // upgrade the elements
Type 2:
$(".data").html("{{content}}").promise().done(function(){
componentHandler.upgradeDom(); // upgrade the newest elements
});
I found the solution in this MDL Github forum post from MDL contributor Jonathan Garbee:
The component handler [ componentHandler.upgradeDom() ] will handle upgrading everything if you just call it with no parameters.
So the pseudo-code of my solution would be:
// Callback function of jquery-ui droppable element
drop: function(event, ui) {
// Add the element from it's template file
$.get("templates/" + elem + ".html", function(data) {
$("#canvas").append(data);
// Expand all new MDL elements
componentHandler.upgradeDom();
});
});
For future readers and users of the Material Design Lite (MDL) framework, you can also refresh dynamically added elements individually (instead of combing the entire DOM).
For example, componentHandler.upgradeDom("mdl-menu")
will upgrade only mdl-menu
elements.
Further reading here.