Mdl components not working when added dynamically

256 views Asked by At

I am making an onclick function and then displaying the progress bar by appending it from javascript. I am also using the material design lite cdn. The components get added but dosen't show up on UI.

Code for progress Bar

var pageContent = document.getElementById("page-content")
    var progressBar = document.createElement("div")
    progressBar.classList.add("mdl-spinner")
    progressBar.classList.add("mdl-js-spinner")
    progressBar.classList.add("is-active")
    progressBar.id = "pBar"
    pageContent.appendChild(progressBar)

Please Help

2

There are 2 answers

3
James A Wilson On

Make sure you added the javascript into the contents of your page: <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>

This script makes the componentHandler available to be called from your javascript. Call this each time you've added elements to the dom.

componentHandler.upgradeDom()

or individually upgrade each element as documented, adding a call to upgradeElement after you dynamically append any child elements to the dom:

var progressBar = document.createElement("div")
    progressBar.classList.add("mdl-spinner")
    progressBar.classList.add("mdl-js-spinner")
    progressBar.classList.add("is-active")
    progressBar.id = "pBar"
    pageContent.appendChild(progressBar)
    componentHandler.upgradeElement(progressBar); //<- add this call
0
Merrin K On

Try this

Just add this code after material components are added.

componentHandler.upgradeDom();