Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically built input using MDL does not render correctly

I have the following code,

var loginForm = document.createElement('div');

loginForm.className = 'row';

loginForm.innerHTML = '<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo"><input class="mdl-textfield__input" type="text" id="login" /><label class="mdl-textfield__label" for="login">Username</label></div>';

document.getElementById('page-content').appendChild(loginForm);

The problem is that since the javascript functions have already ran the input is not styled correctly.

Does anyone what javascript function I need to call to make this work? I tried MaterialTextfield.prototype.init() but nothing changed.

like image 558
Grady D Avatar asked Aug 10 '15 02:08

Grady D


2 Answers

You can use MDL's upgrading element function. Since you have created the loginForm dynamically, you can upgrade it in scope with

    componentHandler.upgradeElement(loginForm);
    //or, componentHandler.upgradeDom(loginForm);
    //however, I suggest using jQuery to upgrade multiple if you are adding more than one
    componentHandler.upgradeElements($('.mdl-textfield').get());

This will get all the mdl-textfield objects and upgrade them (if not upgraded before)

like image 81
Ivan Chau Avatar answered Nov 02 '22 12:11

Ivan Chau


I kept digging through the source code and found componentHandler.upgradeDom(). When running this function all of the dynamic elements are fixed.

like image 34
Grady D Avatar answered Nov 02 '22 12:11

Grady D