Make materialize labels move out of input box when input box is filled via javascript

More specifically, if you are using Materialize in Rails with turbolinks enabled, you will find that Materialize form fields which are prefilled with non-empty values are not active on page load.

The following method worked for me:

$(function() {
    M.updateTextFields();
});

It will add class 'active' to both corresponding labels and prefix icons.


The label transition behavior is triggered by adding the active class to the label's element. Thus, if you make your javascript add that class to the label (e.g. $('label').addClass('active')) in addition to filling in the field, the label will transition out of the field just as it would when selected by a user action.


The document.ready event only fire once when turbolinks is working, so instead you need to tap into the turbolinks load event.

It happens so fast that if you want to see the animation, wrap it in a tiny timeout.

With timeout/visible animation

document.addEventListener('turbolinks:load', () => {
    setTimeout(() => {
        M.updateTextFields();
    }, 100);
});

Without timeout/visible animation

document.addEventListener('turbolinks:load', () => {
    M.updateTextFields();
});

Rails 5 with Turbolinks, and Materialize CSS 1.0.0