Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material Design Lite JS not applied to dynamically loaded html file

I want to unify the navigation layout for my website, so I created a separate html file that holds the code for the navigation. I use a JS to load the file dynamically:

$("#navigation").load("/navigation/navigation.html", function() {
   $.getScript('/material.min.js');
});

The problem is that the material.min.js does not get executed for the dynamically loaded components inside this html and I lose some crucial functionality. How do I fix that?

like image 978
niko Avatar asked Jan 03 '16 17:01

niko


2 Answers

Check if the componentHandler is loaded, and try to upgrade the elements after load.

if(!(typeof(componentHandler) == 'undefined')){
  componentHandler.upgradeAllRegistered();
}

How the Component Handler works

In short this goes over all registered components. Queries for all nodes with the provided CSS class. Loops over those and instantiates them one-by-one. When the upgrade is done on a node, the upgraded object is added to the dataset. This object contains a comma separated list of component classAsString properties to identify which upgrades have been done.

like image 164
Jimmy Pauwaert Avatar answered Nov 14 '22 07:11

Jimmy Pauwaert


From the official docs:

Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the upgradeElement function.

So loading the material.js script again will not execute it. But you can do some experiments with upgradeElements by applying it to the whole loaded markup or to particular elements.

like image 23
Rango Avatar answered Nov 14 '22 06:11

Rango