Documentation

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 style configuration option.

Variant Description
modbox.info(object options) Creates an alert type modal, with an info Bootstrap styled header background.
modbox.success(object options) Creates an alert type modal, with a success Bootstrap styled header background.
modbox.warning(object options) Creates an alert type modal, with a warning Bootstrap styled header background.
modbox.danger(object options) Creates an alert type modal, with a danger Bootstrap 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 input sanitizer option 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 | string

Default: true

Includes a modal-backdrop element. Alternatively, specify 'static' for a backdrop which doesn't close the modal on click.

body

Type: string

This 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 message configuration option is also available. One of the two options is required.

buttons Only available to instance modals

Type: array

Default: []

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 options okButton and closeButton, whereas .alert() and its variants only have closeButton. Both of these special button objects accept the same configuration options below.
Option Type Default Description
callback function null Function 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 class attribute.
close boolean true Whether the modal will automatically close when the button is clicked.
disabled boolean false Adds the disabled attribute.
icon string null Class 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 the label option:
'<span class="material-icons">close</span> Close'
id string 'modbox-btn-[random #]' Sets the id attribute.
label string 'Close' Sets the displayed text (custom HTML markup supported).
outline boolean false Whether to use the outline button style.
size string null Sets an alternate button size. Possible values:
sm, lg
style string 'secondary' Sets the color based on the predefined Bootstrap utility classes. Possible values:
primary, secondary, success, danger, warning, info, light, dark, link
title string null Sets the title attribute.
center

Type: boolean

Default: false

Vertically centers the modal within the viewport.

closeButton Only available to class modals

Type: object

Default: [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 standard buttons object. Also rejects the returned Promise.

destroyOnClose Only available to instance modals

Type: boolean

Default: false

Automaticlly 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: boolean

Default: true

Automatically adds a default button to the footer which closes the modal. This option is ignored if custom buttons are defined with the buttons option. If set to false and no buttons are specified, the modal footer is hidden.

events

Type: object

Default: {}

An object containing event keys and a corresponding callback function. See the Events section for more details.

fade

Type: boolean

Default: true

Animates the modal when shown and hidden.

focus Bootstrap native

Type: boolean

Default: true

Puts the focus on the modal when initialized.

headerCloseStyle

Type: string

Default: null

Sets the style of the header close button ("X"). If null, this will be automatically set to dark or white, depending on the value of the style option. Possible values: dark, white

icon

Type: string

Default: null

Class 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 the title option:
'<span class="material-icons">warning</span> Error'

id

Type: string

Default: 'modbox-[random #]'

Sets the id attribute of the top-level modal element.

input Only available to .prompt() modal

Type: object | string

Default: object

Defines the input field 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 the defaultOptions class/static property.
										
											modbox.defaultOptions = {
												input: {
													...
												}
											};
										
									
Option Type Default Description
autocomplete string 'off' Sets the autocomplete attribute.
class string '' Additional class list that will be added to the class attribute.
id string 'modbox-input-[random #]' Sets the id attribute.
maxlength number null Sets the maxlength attribute.
minlength number null Sets the minlength attribute. If set, the validity of the input field will be checked when clicking the okButton.
pattern string, regexp null Sets the pattern attribute. If set, the validity of the input field will be checked when clicking the okButton. If passing a string, backslashes much be escaped - eg. /\d+/ or '\\d+'.
placeholder string null Sets the placeholder attribute.
required boolean false Adds the required attribute. If true, the validity of the input field will be checked when clicking the okButton.
sanitizer boolean, function false

If true, the input field value will be sanitized using the same function that is defined for the modal sanitizer option, 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 string null Sets the title attribute.
type string 'text' Sets the type attribute.
value string '' Sets the initial value of the input field.
justifyButtons

Type: string

Default: null

Adds 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: boolean

Default: true

Closes the modal when ESC key is pressed.

message

Type: string

Default: ''

Alternate for the body configuration option. One of the two options is required.

okButton Only available to class modals

Type: object

Default: [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 standard buttons object. Also resolves the returned Promise, and in the case of .prompt(), the value of the input field is passed to the resolve() function.

Calling event.preventDefault() from within the callback function will prevent the Promise from resolving.

relatedTarget

Type: element

Default: undefined

Sets the relatedTarget property on the event object passed to show and shown event callback functions. Can be overridden by passing in an element when calling the .show() method.

sanitizer

Type: function

Default: [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: boolean

Default: true

Allows long content of the modal body to scroll as opposed to scrolling the viewport.

show Only available to instance modals

Type: boolean

Default: false

Whether 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: boolean

Default: true

Whether the close button ("X") is shown in the modal header. This option has no effect if the header is hidden (title is null or empty string).

size

Type: string

Default: null

Sets an alternate size for the modal. Possible values: sm, lg, xl, fullscreen

style

Type: string

Default: '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: boolean

Default: false

Reverses 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: string

Default: 'Information'

Sets the text displayed in the modal header (custom HTML markup supported). If set to null or an empty string, the header will be hidden.

titleStyle

Type: string

Default: null

Sets the title text color based on the predefined Bootstrap utility classes. If null, this will be automatically set to dark or white, depending on the value of the style option. 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: array

An array of button elements in the footer of the modal.

modal

Type: object

The native bootstrap modal object.

modalEl

Type: element

The top-level .modal DOM element.

options

Type: object

The 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: function

Getter 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: element

The #modbox-container DOM element that holds all modboxes.

defaultOptions

Type: object

Getter or setter. Returns the current default modal configuration options, or allows you to overwrite them for future modals. Button options set by buttons, okButton, and closeButton have precedence over defaultButtonOptions

										
											console.log(modbox.defaultOptions);
											// or
											modbox.defaultOptions = {
												style: 'info',
												center: true,
												closeButton: {
													label: 'Go Away!'
												}
											};
										
									

defaultButtonOptions

Type: object

Getter 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: string

The 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 button

Appends a button to the footer of the modal. If the swapOrder argument is true (default false) or the swapButtonOrder option was true when 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, the swapOrder argument will always override the swapButtonOrder config option. See the buttons options 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.modal event 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.modal event occurs). Also, you can pass a DOM element as an argument that can be received in the modal events (as the relatedTarget property). If no element is passed, the relatedTarget modal 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.modal or hidden.bs.modal event occurs).

Class/Static Methods

The following methods are available to the modbox class.

alert(object options)

Returns: promise

Creates an alert type modal.

confirm(object options)

Returns: promise

Creates a confirm type modal.

danger(object options)

Returns: promise

Creates an alert type modal, with a danger Bootstrap styled header background.

error(object options)

Returns: promise

Alternate method name for the .danger() modal.

getInstance(element modal) Bootstrap native

Returns: object modal

Get the modal instance associated with a DOM element.

getOrCreateInstance(element modal) Bootstrap native

Returns: object modal

Get the modal instance associated with a DOM element, or create a new one in case it wasn't initialized.

info(object options)

Returns: promise

Creates an alert type modal, with an info Bootstrap styled header background.

prompt(object options)

Returns: promise

Creates 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. The modalType argument 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: promise

Creates an alert type modal, with a success Bootstrap styled header background.

warning(object options)

Returns: promise

Creates an alert type modal, with a warning Bootstrap 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.