I'm using the new material-design-lite (mdl) on my website. I'm also loading in dynamic content using mustache.js.
Now, the newly created elements need to be registered with using the upgradeElement
function for mdl to know of them and apply the javascript to them. On their website they have some sample code to do this:
<div id="container"/>
<script>
var button = document.createElement('button');
var textNode = document.createTextNode('Click Me!');
button.appendChild(textNode);
button.className = 'mdl-button mdl-js-button mdl-js-ripple-effect';
componentHandler.upgradeElement(button);
document.getElementById('container').appendChild(button);
</script>
However, I am using jQuery and I'm not entirely sure how I should parse the whole template I get from mustache.js
and register each component correctly. This is what I've tried:
var filledTemplate = '
<div class="mdl-card mdl-shadow--2dp">
<div class="mdl-card__title">
<h2 class="mdl-card__title-text">Title</h2>
</div>
<div class="mdl-card__supporting-text">
<p>A simple paragraph with below some radio buttons</p>
<p>
<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="input_0">
<input type="radio" id="input_0" class="mdl-radio__button" name="options" value="radio1" />
<span class="mdl-radio__label">Radio button 1</span>
</label>
</p>
<p>
<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="input_1">
<input type="radio" id="input_1" class="mdl-radio__button" name="options" value="radio2" />
<span class="mdl-radio__label">Radio button 2</span>
</label>
</p>
</div>
<div class="mdl-card__actions mdl-card--border">
<a class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect">
Send
</a>
</div>
</div>';
var html = $.parseHTML(filledTemplate);
$(html).find(".mdl-js-button").each(function(){
componentHandler.upgradeElement($(this));
});
The filledTemplate
is just to give a clear idea of the stuff it can contain. I need to bind all input's, textareas, sliders, radios, checkboxes and a button. In the example above you can see a simple card-layout from mdl, with two radio boxes and a button.
I tried to get the componentHandler to upgrade the button-element first, but mdl returns element.getAttribute is not a function
, so I guess I'm just giving the wrong value to .upgradeElement()
.
What am I doing wrong here?
Here is a codepen as an example: http://codepen.io/anon/pen/JdByGZ