MaterializeCSS Modal Initialization and Cleanup in Vanilla JavaScript
MaterializeCSS modals require explicit M.Modal.init() before use. This guide covers initialization options, dynamic instance handling, cleanup with destroy(), and common pitfalls like double-initialization and positioning inside transformed parents.
30 Apr 2026, 08:36 UTC

The Core Problem
MaterializeCSS modals do not activate from markup alone. A modal element with the modal class and an id will sit inert until you explicitly create a JavaScript instance via M.Modal.init(). This catches developers who expect the framework to auto-wire components like Bootstrap or who copy jQuery-era snippets that no longer apply to the 1.x vanilla API.
The practical takeaway: always initialize before calling open() or close(), retain the returned instance for later control, and call destroy() when removing the modal from the DOM to avoid memory leaks in single-page applications.
Worked Initialization Example
Include the compiled CSS and JS (tested with Materialize 1.0.0):
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>Markup for a basic modal:
<div id="confirm-delete" class="modal">
<div class="modal-content">
<h4>Confirm Deletion</h4>
<p>This action cannot be undone.</p>
</div>
<div class="modal-footer">
<a href="#" class="modal-close waves-effect waves-green btn-flat">Cancel</a>
<button id="confirm-btn" class="waves-effect waves-red btn-flat">Delete</button>
</div>
</div>Initialize with options and open programmatically:
const modalEl = document.getElementById('confirm-delete');
// Guard against double-initialization
let instance = M.Modal.getInstance(modalEl);
if (!instance) {
instance = M.Modal.init(modalEl, {
dismissible: false, // prevent close on overlay click
startingTop: '10%', // animation start position
endingTop: '10%', // final position
onCloseStart: () => console.log('Closing...'),
onCloseEnd: () => console.log('Closed')
});
}
// Later, open when needed
instance.open();Run this in a browser console after the DOM loads. The modal appears centered at 10% from the top, and the overlay click will not dismiss it because dismissible: false.
Instance Management for Dynamic Modals
M.AutoInit() runs on DOMContentLoaded and initializes components present in the initial HTML. Modals injected after page load—via fetch, template rendering, or framework routers—require manual initialization.
Typical pattern in a fetch-then-render flow:
async function showUserModal(userId) {
const html = await fetch(`/user-modal/${userId}`).then(r => r.text());
const container = document.createElement('div');
container.innerHTML = html;
document.body.appendChild(container.firstElementChild);
const modalEl = document.getElementById(`user-modal-${userId}`);
const instance = M.Modal.init(modalEl, { dismissible: true });
instance.open();
// Return instance so caller can destroy later
return instance;
}Store the returned instance in a component registry or React ref / Vue ref so you can call instance.close() or instance.destroy() when the user navigates away.
Cleanup and Memory Leak Prevention
When a modal element is removed from the DOM, its event listeners (overlay click, keydown for ESC, resize handlers) remain attached unless you call destroy(). In long-running SPAs this accumulates stale listeners and references.
function removeModal(instance, modalEl) {
if (instance && modalEl) {
instance.destroy(); // detaches listeners, clears internal refs
modalEl.remove(); // safe to remove from DOM after destroy
}
}Verification: open DevTools → Elements → select the modal element → Event Listeners tab. After destroy() and removal, no Materialize listeners should remain on the overlay or document.
Common Mistakes and Limits
1. Re-initializing an existing instance
Calling M.Modal.init() on an element that already has an instance may throw or return the existing instance depending on version. Always check first:
const existing = M.Modal.getInstance(modalEl);
if (existing) return existing;
return M.Modal.init(modalEl, options);2. Positioning inside transformed or fixed parents
Materialize positions modals with position: fixed relative to the viewport. If your modal markup lives inside a parent with transform, filter, or will-change, the fixed positioning context shifts and the modal may appear off-screen or misaligned. Fix: move modal markup to be a direct child of <body> before initialization.
3. jQuery-style code does not work
Snippets like $('#modal').modal('open') or $('.modal').modal() are from pre-1.0 releases. The 1.x API is vanilla-only; jQuery is not a dependency and the plugin bridge was removed.
4. Maintenance mode reality
MaterializeCSS has not had a major feature release since 2018. Integration with modern bundlers (Vite, Webpack 5), TypeScript definitions, or newer browser APIs (top-layer, dialog element) lacks official guidance. Community forks exist but diverge.
Quick Verification Checklist
- Load
materialize.cssandmaterialize.jsin a test page. - Add the modal markup above with a unique
id. - Open console and run:
const el = document.getElementById('confirm-delete'); const inst = M.Modal.init(el); inst.open(); - Confirm modal appears, overlay click behavior matches
dismissibleoption. - Run
inst.close()theninst.destroy()and verify no listeners remain in DevTools.
When to Consider Alternatives
If you need native <dialog> semantics, top-layer management, or TypeScript-first APIs, evaluate libraries like Radix UI or Headless UI. MaterializeCSS modals remain viable for maintenance projects already using the framework, but new projects should weigh the maintenance-mode status against modern alternatives.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.