Modals
The bootstrap-modbox library provides several convenience class methods to easily create alert, confirm, and prompt type modals. These mimic the browser dialogs that can be called by their respective JavaScript functions, except for the fact that, like native Bootstrap modals, they're asyncronous - meaning they do not block the browser thread.
In addition, custom and more advanced instance modals may be created by calling the constructor directly (new modbox(options)).
Information
All of the class modal methods return a Promise, whereas calling the constuctor does not. For.confirm() and .prompt(), the Promise is resolved when clicking the okButton, and rejected when the modal is closed in any other way (closeButton, 'X', ESC key, clicking the backdrop, etc). For .alert() and its variants, which only have the single closeButton, the Promise is always resolved.
- modbox.alert(
object options) -
Creates an alert type modal. In addition, there are several methods that create variants of this modal which are all functionally identical, but serve as shortcuts to different header styles. Alert modals using other styles not defined as method variants may be created by passing the
styleconfiguration option.Variant Description modbox.info(object options)Creates an alert type modal, with an infoBootstrap styled header background.modbox.success(object options)Creates an alert type modal, with a successBootstrap styled header background.modbox.warning(object options)Creates an alert type modal, with a warningBootstrap styled header background.modbox.danger(object options)Creates an alert type modal, with a dangerBootstrap styled header background.modbox.error(object options)Alternate method name for the .danger()modal. - modbox.confirm(
object options) - Creates a confirm type modal.
- modbox.prompt(
object options) -
Creates a prompt type modal. The value of the input field is passed to the Promise
resolve()function.Important
The input value returned when the Promise is resolved is not sanitized in any way by default. If the intent is to store or process this data, it is your responsibility to make sure it is safe. See the documentation for the inputsanitizeroption as an available solution. - new modbox(
object options) - Creates a modbox instance. Lacks the extra scaffolding present in the class/static methods above, which allows for the creation of custom and more advanced modals. Returns a modbox object.
Options
A configuration object to be passed in to any modbox modal. If a string is passed in place of the options object when creating a modbox, it will be used as the body.
- backdrop Bootstrap native
-
Type:
boolean|stringDefault:
trueIncludes a modal-backdrop element. Alternatively, specify
'static'for a backdrop which doesn't close the modal on click. - body
-
Type:
stringThis option is required
A string consisting of plain text or HTML markup which will be used as the main body of the modal. As an alternate, the
messageconfiguration option is also available. One of the two options is required. - buttons Only available to instance modals
-
Type:
arrayDefault:
[]Each item in the array is an object defining the button configuration. If a custom or more advance button is necessary, a string containing the HTML markup may be passed instead of the configuration object.
Important
This option is only available to modal instances created by calling the constructor directly (new modbox(options)). The class modals.confirm()and.prompt()instead have the special optionsokButtonandcloseButton, whereas.alert()and its variants only havecloseButton. Both of these special button objects accept the same configuration options below.Option Type Default Description callback functionnullFunction to be called when the button is clicked. It is passed two arguments: the event object, and the modbox instance object. Also, the function context ( this) is set to the button element.class string''Additional class list that will be added to the button's classattribute.close booleantrueWhether the modal will automatically close when the button is clicked. disabled booleanfalseAdds the disabledattribute.icon stringnullClass list (eg. 'fas fa-times') used to add an icon to the button. The markup injected is for use by icon font libraries matching the pattern<i class="fas fa-times"></i>(Font Awesome, Material Design, etc). Otherwise, if you are using ligatures or non-font based icon sets (img, svg, etc), the markup can be manually added to thelabeloption:'<span class="material-icons">close</span> Close'id string'modbox-btn-[random #]'Sets the idattribute.label string'Close'Sets the displayed text (custom HTML markup supported). outline booleanfalseWhether to use the outline button style. size stringnullSets an alternate button size. Possible values: sm, lgstyle string'secondary'Sets the color based on the predefined Bootstrap utility classes. Possible values: primary, secondary, success, danger, warning, info, light, dark, linktitle stringnullSets the titleattribute. - center
-
Type:
booleanDefault:
falseVertically centers the modal within the viewport.
- closeButton Only available to class modals
-
Type:
objectDefault:
[default button]Configuration for the "Close" button. This is a special option only available to the class modals
.alert()(and variants),.confirm(), and.prompt(). Accepts the same configuration options as a standardbuttonsobject. Also rejects the returned Promise. - destroyOnClose Only available to instance modals
-
Type:
booleanDefault:
falseAutomaticlly calls the
destroy()method when the modal is closed. This option is ignored for the class modals.alert(),.confirm(), and.prompt(), as they are always destroyed on close. - defaultButton Only available to instance modals
-
Type:
booleanDefault:
trueAutomatically adds a default button to the footer which closes the modal. This option is ignored if custom buttons are defined with the
buttonsoption. If set tofalseand nobuttonsare specified, the modal footer is hidden. - events
-
Type:
objectDefault:
{}An object containing event keys and a corresponding callback function. See the Events section for more details.
- fade
-
Type:
booleanDefault:
trueAnimates the modal when shown and hidden.
- focus Bootstrap native
-
Type:
booleanDefault:
truePuts the focus on the modal when initialized.
- headerCloseStyle
-
Type:
stringDefault:
nullSets the style of the header close button ("X"). If
null, this will be automatically set todarkorwhite, depending on the value of thestyleoption. Possible values:dark, white - icon
-
Type:
stringDefault:
nullClass list (eg.
'fas fa-exclamation-triangle') used to add an icon to the modal header. The markup injected is for use by icon font libraries matching the pattern<i class="fas fa-exclamation-triangle"></i>(Font Awesome, Material Design, etc). Otherwise, if you are using ligatures or non-font based icon sets (img, svg, etc), the markup can be manually added to thetitleoption:'<span class="material-icons">warning</span> Error' - id
-
Type:
stringDefault:
'modbox-[random #]'Sets the
idattribute of the top-level modal element. - input Only available to .prompt() modal
-
Type:
object|stringDefault:
objectDefines the
inputfield element that will be added to the modal body. This is a special option only available to the class modal.prompt().If a custom or more advance field is necessary, a string containing HTML markup may be passed instead of the configuration object. However, please note that if a custom field is used, its value will not be passed to the Promise
resolve()function, and any necessary validation and/or logic must be handled manually (modal events, button callbacks, etc).Note
Defaults can be changed by use of thedefaultOptionsclass/static property.modbox.defaultOptions = { input: { ... } };Option Type Default Description autocomplete string'off'Sets the autocompleteattribute.class string''Additional class list that will be added to the classattribute.id string'modbox-input-[random #]'Sets the idattribute.maxlength numbernullSets the maxlengthattribute.minlength numbernullSets the minlengthattribute. If set, the validity of the input field will be checked when clicking theokButton.pattern string, regexpnullSets the patternattribute. If set, the validity of the input field will be checked when clicking theokButton. If passing a string, backslashes much be escaped - eg./\d+/or'\\d+'.placeholder stringnullSets the placeholderattribute.required booleanfalseAdds the requiredattribute. Iftrue, the validity of the input field will be checked when clicking theokButton.sanitizer boolean, functionfalseIf
true, the input field value will be sanitized using the same function that is defined for the modalsanitizeroption, before being passed to the Promise resolve function (see documentation). Alternatively, a separate function may be supplied, which differs from the modal option.// strip all html tags from input modbox.prompt({ ... input: { sanitizer: (input) => input.replace(/(<([^>]+)>)/gi, '') } });title stringnullSets the titleattribute.type string'text'Sets the typeattribute.value string''Sets the initial value of the input field. - justifyButtons
-
Type:
stringDefault:
nullAdds Bootstrap flex utility classes to the modal footer to alter the alignment of the buttons. Possible values:
start, end, center, between, around, evenly - keyboard Bootstrap native
-
Type:
booleanDefault:
trueCloses the modal when ESC key is pressed.
- message
-
Type:
stringDefault:
''Alternate for the
bodyconfiguration option. One of the two options is required. - okButton Only available to class modals
-
Type:
objectDefault:
[default button]Configuration for the "OK" button. This is a special option only available to the class modals
.confirm()and.prompt(). Accepts the same configuration options as a standardbuttonsobject. Also resolves the returned Promise, and in the case of.prompt(), the value of the input field is passed to theresolve()function.Calling
event.preventDefault()from within the callback function will prevent the Promise from resolving. -
Type:
elementDefault:
undefinedSets the
relatedTargetproperty on the event object passed toshowandshownevent callback functions. Can be overridden by passing in an element when calling the.show()method. - sanitizer
-
Type:
functionDefault:
[placeholder function]This library builds its markup as a string, then uses the
element.insertAdjacentHTML()method to parse and inject the resulting nodes into the DOM. There has been some concern shown for other libraries using similar methods (element.insertHTML, jQuery$(element).html(), etc) that this could be a potential XSS attack vector (eg. user submitted data), considering that custom markup can be passed as a string with some configuration options (title, body, etc).This option accepts a function, which can be from an external library like DOMPurify (for example), that can be used to sanitize the modal markup string before parsing and inserting into the DOM. The default placeholder function simply returns the markup string unmodified.
If used, it is recommended to set a sanitizer function in the
defaultOptions, so it will be applied to all modals.modbox.defaultOptions = { ... sanitizer: DOMPurify.sanitize }; - scrollable
-
Type:
booleanDefault:
trueAllows long content of the modal body to scroll as opposed to scrolling the viewport.
- show Only available to instance modals
-
Type:
booleanDefault:
falseWhether the modal will be shown immediately upon creation. This option is ignored for the class modals
.alert(),.confirm(), and.prompt(), as they are always shown immediately. - showHeaderClose
-
Type:
booleanDefault:
trueWhether the close button ("X") is shown in the modal header. This option has no effect if the header is hidden (
titleisnullor empty string). - size
-
Type:
stringDefault:
nullSets an alternate size for the modal. Possible values:
sm, lg, xl, fullscreen - style
-
Type:
stringDefault:
'white'Sets the header background color based on the predefined Bootstrap utility classes. Possible values:
primary, secondary, success, danger, warning, info, light, dark, body, white - swapButtonOrder
-
Type:
booleanDefault:
falseReverses the order of the buttons in the modal footer. This setting also affects where new buttons are appended when using the
.addButton()method. - title
-
Type:
stringDefault:
'Information'Sets the text displayed in the modal header (custom HTML markup supported). If set to
nullor an empty string, the header will be hidden. - titleStyle
-
Type:
stringDefault:
nullSets the title text color based on the predefined Bootstrap utility classes. If
null, this will be automatically set todarkorwhite, depending on the value of thestyleoption. Possible values:primary, secondary, success, danger, warning, info, light, dark, body, white, muted
Properties
Unless otherwise specified, all properties are read-only.
Instance Properties
The following properties can be referenced on any instance of a modbox object.
- buttons
-
Type:
arrayAn array of button elements in the footer of the modal.
- modal
-
Type:
objectThe native bootstrap modal object.
- modalEl
-
Type:
elementThe top-level
.modalDOM element. - options
-
Type:
objectThe options configuration object that was used to create the modbox modal.
Class/Static Properties
The following properties are available to the modbox class.
- bootstrapModal
-
Type:
functionGetter or setter. Return or define a reference to the Bootstrap Modal class. Modbox will automatically attempt to locate a reference in the global namespace, and this is only recommended if loading Bootstrap as a module.
- container
-
Type:
elementThe
#modbox-containerDOM element that holds all modboxes. - defaultOptions
-
Type:
objectGetter or setter. Returns the current default modal configuration options, or allows you to overwrite them for future modals. Button options set by
buttons,okButton, andcloseButtonhave precedence overdefaultButtonOptionsconsole.log(modbox.defaultOptions); // or modbox.defaultOptions = { style: 'info', center: true, closeButton: { label: 'Go Away!' } }; - defaultButtonOptions
-
Type:
objectGetter or setter. Returns the current default button configuration options, or allows you to overwrite them for future buttons.
console.log(modbox.defaultButtonOptions); // or modbox.defaultButtonOptions = { outline: true, callback: () => console.log('You clicked a button'); }; - version
-
Type:
stringThe version of the modbox library being used.
Methods
Instance Methods
The following methods can be called on any instance of a modbox object.
- addButton(
object options,boolean swapOrder) -
Returns:
element buttonAppends a button to the footer of the modal. If the
swapOrderargument istrue(defaultfalse) or theswapButtonOrderoption wastruewhen the modal was created, new buttons will be added as the first child of the footer (to the left), otherwise they will be added as the last child (to the right). However, theswapOrderargument will always override theswapButtonOrderconfig option. See thebuttonsoptions for more details.const newButton = myModbox.addButton({ label: 'New Button' }); - addEvent(
string type,function callback) -
Add an event to the modal. See the Events section for more details.
myModbox.addEvent('hide', () => console.log('hiding modal')); - destroy()
-
Completely deletes the modal. Calls
.dispose()to clean up the stored data, and removes applicable elements from the DOM. - dispose() Bootstrap native
-
Destroys an element's modal. (Removes stored data on the DOM element)
- handleUpdate() Bootstrap native
-
Manually readjust the modal's position if the height of a modal changes while it is open (i.e. in case a scrollbar appears).
- hide() Bootstrap native
-
Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the
hidden.bs.modalevent occurs). - show(
element relatedTarget) Bootstrap native -
Manually opens a modal. Returns to the caller before the modal has actually been shown (i.e. before the
shown.bs.modalevent occurs). Also, you can pass a DOM element as an argument that can be received in the modal events (as therelatedTargetproperty). If no element is passed, therelatedTargetmodal configuration option will be used instead (if set). - toggle() Bootstrap native
-
Manually toggles a modal. Returns to the caller before the modal has actually been shown or hidden (i.e. before the
shown.bs.modalorhidden.bs.modalevent occurs).
Class/Static Methods
The following methods are available to the modbox class.
- alert(
object options) -
Returns:
promiseCreates an alert type modal.
- confirm(
object options) -
Returns:
promiseCreates a confirm type modal.
- danger(
object options) -
Returns:
promiseCreates an alert type modal, with a
dangerBootstrap styled header background. - error(
object options) -
Returns:
promiseAlternate method name for the
.danger()modal. - getInstance(
element modal) Bootstrap native -
Returns:
object modalGet the modal instance associated with a DOM element.
- getOrCreateInstance(
element modal) Bootstrap native -
Returns:
object modalGet the modal instance associated with a DOM element, or create a new one in case it wasn't initialized.
- info(
object options) -
Returns:
promiseCreates an alert type modal, with an
infoBootstrap styled header background. - prompt(
object options) -
Returns:
promiseCreates a prompt type modal.
- setDefaults(
string modalType,object modalOptions) -
Allows setting default options independently for each modal type. Inherits from and overwrites options set by
modbox.defaultOptions. ThemodalTypeargument can be any of the available types of class/static modals:alert,info,success,warning,danger,confirm,prompt. Does not affect instance modals created by calling the constructor. - success(
object options) -
Returns:
promiseCreates an alert type modal, with a
successBootstrap styled header background. - warning(
object options) -
Returns:
promiseCreates an alert type modal, with a
warningBootstrap styled header background.
Events
All native Bootstrap events are supported through the events configuration option, or by calling the addEvent() instance method. The callback functions are passed two arguments: the event object, and the modbox instance object. Also, the function context (this) is set to the top-level .modal DOM element.
new modbox({
events: {
shown: (event, modal) => console.log('modal shown'),
hidden: (event, modal) => console.log('modal hidden')
}
});
| Type | Bootstrap Event | Description |
|---|---|---|
show |
show.bs.modal |
This event fires immediately when the show() instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event. |
shown |
shown.bs.modal |
This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). If caused by a click, the clicked element is available as the relatedTarget property of the event. |
hide |
hide.bs.modal |
This event is fired immediately when the hide() instance method has been called. |
hidden |
hidden.bs.modal |
This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete). |
hidePrevented |
hidePrevented.bs.modal |
This event is fired when the modal is shown, its backdrop is static, and a click outside the modal or the ESC key press is performed with the keyboard option set to false. |