Initialization

Many Materialize components require initialising. If you forget to initialize, the component will not work. Look out for the <> icon – this is to indicate that the component must be initialized. There are 3 ways to initialize:

  1. Javascript
  2. jQuery
  3. autoInit()
Javascript

Because jQuery is no longer a dependency of Materialize, all components can be initialized using vanilla javascript. You do not need to include jQuery in your project. For example, to initialize a select element, you would use:

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
  });

Most components come with a variety of setup options, where we can load data and modifications. To use options, we pass an object ( a collection of key/value pairs) as a second argument, like this, which gives the select wrapper a class of my-class.

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems, {
        classes:'my-class'
    });
  });

Your Javascript file should only contain one DOMContentLoaded – all the initialisations and custom code go inside this single function.

jQuery

If you decide to take advantage of jQuery, you can use a much shorter syntax for the initialisation, but some methods will be unavailable. The jQuery equivalent for the a select input would be:

$(document).ready(function(){
    $('select').formSelect();
  });

// with options:

$(document).ready(function(){
    $('select').formSelect({
       classes:'my-class'
    });
  });
Suggest an edit

If you think this page contains an error or could be improved - or you have a suggestion for a new article, drop me a message!

Spread the love