Search code examples
javascriptjquerymaterial-design-lite

Modifying MDL elements on page load


I am trying to set the value of a mdl slider when a page loads. The recommended way of setting the value for a mdl slider is like this-

document.querySelector('#slider').MaterialSlider.change(value);

This however throws an error TypeError: document.querySelector(...).MaterialSlider is undefined if called from $(document).ready() or $(window).load().

Setting a timeout of a second on it fixes the issue but seems hacky. Is there any other event I can tie it to to ensure it works?

This is how I am loading the scripsts --

    //mobile optimized
    meta(name='viewport', content='width=device-width, initial-scale=1.0')

    //css
    link(rel='stylesheet', href='/stylesheets/style.css')

    //material-design-lite
    link(rel='stylesheet', href='/bower_components/material-design-lite/material.min.css')
    script(src='/bower_components/material-design-lite/material.min.js')
    link(rel='stylesheet', href='https://fonts.googleapis.com/icon?family=Material+Icons')

    //jQuery
    script(src='/bower_components/jquery/dist/jquery.min.js')

    //Material icon fonts
    //link(rel="stylesheet", href="https://fonts.googleapis.com/icon?family=Material+Icons")
    link(href='https://fonts.googleapis.com/css?family=Open+Sans', rel='stylesheet', type='text/css')

    //polyfill (support for dialog)
    script(src="/bower_components/dialog-polyfill/dialog-polyfill.js")
    link(rel="stylesheet", type="text/css", href="/bower_components/dialog-polyfill/dialog-polyfill.css")

Solution

  • It took me a few months but I finally found a solution to this. Just needed to add this --

    $( document ).ready(function() {
        componentHandler.upgradeAllRegistered();
        // --- do stuff on mdl elements here ---
    });
    

    This has the added advantage of hiding the ugly version of the mdl components before they are fully loaded.