Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MDL ready event

MDL is upgrading its components upon page load, so <input> with autofocus attribute looses its focus. I want to set a focus on this input after MDL finishes rerendering.

I'm trying to listen to some page ready event (codepen):

$('input#srch').one('componentDidUpdate', function(){console.log('ready')});

Not working neither with $(document) nor $(document.body) nor $('.mdl-layout') selectors.
I've googled for some similar events but no luck, am I missing something?
Sure I can use setTimeout but I don't think that should be a solution 😁

like image 799
mu3 Avatar asked Feb 18 '16 20:02

mu3


2 Answers

You can listen to the mdl-componentupgraded event on the layout element, .mdl-ayout.

$(document).ready(function() {
    $('.mdl-layout').on('mdl-componentupgraded', function(e) {
        if ($(e.target).hasClass('mdl-layout')) {
            alert('ready');
        }
    });
});

Use on instead of one. Your page might have multiple elements being upgraded. By using one you are going to catch only the first upgrade. With on the handler will be called multiple times because of event bubbling. Check e.target to react to the specific upgrade of the layout element.

Use a $(document).ready() callback. Wait for the DOM to be ready before attaching handlers to its elements. Otherwise the $('.mdl-layout') selector might not match and the event handler might not attach.

like image 78
Rafa Avatar answered Oct 18 '22 12:10

Rafa


/* Check if the material design has finished the rendering */

var mdlLoaded = setInterval(function(){ 
    if(typeof document.querySelector('.mdl-js-layout') !== 'undefined') init()
}, 100)

function init () { 
    clearInterval(mdlLoaded)
    alert('ready')
}
like image 26
Marvin Medeiros Avatar answered Oct 18 '22 12:10

Marvin Medeiros