19

I'm working with Google Material Design components which are stripped down for simplicity, then rendered more fully when the page is loaded. Simplified below to illustrate the issue:

What shows in the index.html file:

<div class="switch"></div>

What renders to the DOM when the page is loaded:

<div class="switch">
   <div class="switch_track"></div>
   <div class="switch_thumb"></div>
</div>

I am creating a drag and drop HTML editor and have template files for each component type. The template file for a switch is simply:

switch.html

<div class="switch"></div>

The problem is when I drag this to the canvas. jQuery looks at switch.html and renders <div class="switch"></div> to the DOM, but since it was dynamically added, it is not being "seen" by the scripts that added the additional track and thumb tags.

How can I fix this issue so that whenever the DOM is updated, it reruns any scripts? Ideally I would like to avoid touching any of the Material Design script files.

Jon
  • 3,154
  • 13
  • 53
  • 96
  • http://stackoverflow.com/questions/10912925/reloading-an-html-element-with-a-javascript-function. Have you checked this post already? – Lucas Piske Sep 02 '15 at 22:04

2 Answers2

39

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.

Jon
  • 3,154
  • 13
  • 53
  • 96
1

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 
 });
Karthikeyan Ganesan
  • 1,901
  • 20
  • 23