Dhruv Aggarwal
Dhruv Aggarwal

Reputation: 53

Mdl components not working when added dynamically

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

Upvotes: 1

Views: 272

Answers (2)

Merrin K
Merrin K

Reputation: 1790

Try this

Just add this code after material components are added.

componentHandler.upgradeDom();

Upvotes: 1

James A Wilson
James A Wilson

Reputation: 14701

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

Upvotes: 1

Related Questions