Search code examples
javascripthtmljquerymodal-dialogmaterialize

How to detect for a MaterializeCSS modal closing?


I have multiple Materialize CSS modals on my site and each one of them has a different search bar. I want the website to detect when a modal is closed so I can reset the value of the search bar. I know how to reset the value, but I am having trouble with detecting a modal closing. What is the simplest JS/jQuery way of doing it?

P.S. There is a lot of code that is interconnected so I didn't attach it here and I think it is not really necessary since this is a general problem, not just with a specific modal.


Solution

  • Super easy:

     document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.modal');
        var instances = M.Modal.init(elems,{
          onCloseEnd: function() {
            console.log('Modal closed');
          },
          onOpenEnd: function(){
             console.log('Modal Open');
          }
        });
      });
    

    When you initialize the modal, you can pass options (as an object {}), and M provides a bunch of useful hooks. If you need to detect a specific modal, you can check the id or any other data using this:

    onOpenEnd: function(){
           console.log(this.id+' Modal Open');
    }
    

    Codepen

    Docs.