Modal.mjs is a simple, lightweight and easy to use module for creating modals with JavaScript.
See Modal.mjs in action:
- Become a customer form on deltaco.se
- DELTACO OFFICE Configurator with a custom theme
It also has dark theme support - enabled with a CSS Media feature.
Method 1:
- Clone this repo into a lib folder
- Import the stylesheet
modal-mjs/modal.css(CSS@import, HTML<link>etc.)
@import url("../lib/modal-mjs/modal.css");- Import the module
modal-mjs/Modal.mjswhere you need it
import { Modal } from "./lib/modal-mjs/Modal.mjs";Method 2:
- Clone this repo or download it as a zip
- Copy the
modal.cssstylesheet into your css folder - Import the stylesheet with CSS
@import, HTML<link>etc.
@import url("modal.css");- Copy the
Modal.mjsmodule into your JSmodules/ - Import the module from your JavaScript where you need it
import { Modal } from "./modules/Modal.mjs";Modals build their own element tree when opened. You don't need to add anything to your DOM.
This is the simplest and fastest way to create a modal:
const modal = new Modal("Header text");
modal.open("<p>Content text</p>");See the Methods section for a more detailed explanation.
You can append HTML to a modal with the append() method before the modal has been openend with open().
This can be useful if your program doesn't have all the UI components to show in a modal at the time of construction.
const modal = new Modal("Product summary");
products.forEach(product => modal.append(`<li>${product}</li>`));
modal.open();The Modal class takes a single, optional argument which when defined; will open the modal with a heading and close button.
const modal = new Modal();Omitting this argument will open the modal without a header, heading and close button. This "slim mode" is great for loading spinners and CTA.
A modal opened without a header has to be closed by calling close().
Calling this method will insert the modal element tree into the DOM and open it with a transition.
Calling append() will no longer have an effect.
modal.open();You can pass an HTML string to this method as an optional argument and the modal will open immediately with that content.
modal.open("<p>Hello world</p>");Close the modal with a transition and remove it from the DOM.
modal.close();This method can also be called from the prototype of a modal element.
<div id="myModal" class="modal"></div>document.getElementById("myModal").close();Append HTML to the modal body. Call open() when you've appended all HTML to show the modal.
modal.append("<p>lorem ipsum</p>");
modal.append("<p>dolor sit amet</p>");
//...
modal.open();The modal HTMLElements can be accessed and modified before and after a modal has been opened with open().
console.log(modal.wrapper); // HTMLElement of the modal parent
console.log(modal.inner); // HTMLElement of the inner containerThis also means you can read, modify and set properties just like you would on any other element.
modal.inner.style.setProperty("background-color","red");