new Modal()
- Allows you to add dialogs to your site for lightboxes, user notifications, custom content and etc...
- Nested modals aren’t supported. Avoid nesting modals in fixed elements. The modals
use
position: fixed
, which can sometimes be a bit particular about its rendering. - When possible, place your modal HTML in a top-level position to avoid interference from other elements.
- Each modal should have a unique
id
attribute. - When a modal is opened the class name
js-modal-opened
is appended to the<html>
. - You can show modals via
data-modal
or JavaScript. - You can listen to custom events fired by the modal. See example below.
- See it in action + some notes! 😀
Event Name | Description |
---|---|
modal.opened |
Triggered when a modal is opened. Returns the modal. |
modal.closed |
Triggered when a modal is closed. Returns the modal. |
Examples
Sample markup of modal HTML.
<div class="modal" id="unique-id3"> <div class="modal-header"> <h2 class="modal-header-title">Modal header</h2> <a href="#" class="modal-close">Close me</a> </div> <div class="modal-content"> <p>Modal content.</p> </div> </div>
You can show modals via data attribute, data-modal="width:700"
.
The only lines of JavaScript would be two lines. The rel
attribute needs to equal
the ID of the modal HTML element.
<a href="#" rel="unique-id3" data-modal="width:700">open modal</a> // Only JavaScript needed: <script> var modals = new ML.Modal(); modals.init(); </script> // Other javascript files go here.
The modal can be triggered via JavaScript instead of or in addition
to data-modal
// Will show the modal HTML with id of unique-id3 with a width of 750 pixels modals.show('unique-id3', {width: 750});
Using custom events.
document.addEventListener('modal.opened', function(event) { var eventDetails = event.detail; console.log('opened modal', eventDetails.modal); });
Methods
-
destroy()
-
Destroys the modal init.
Example
modals.destroy();
-
hide()
-
Hides all the modals.
Example
modals.hide();
-
init()
-
Initializes the modal class.
Example
modals.init();
-
show(id, modalOptions)
-
Shows a modal. Used when showing modal without
data-modal
.Parameters:
Name Type Description id
String The id of the modal you want to display.
modalOptions
Object Configuration settings to overwrite defaults. Only
width
will be overriden. Other settings are ignored.