How to Use the modal component of Bootstrap to customize alert, confirm, and modal dialogs _ javascript skills

Source: Internet
Author: User
This article will introduce Modal, a pop-up window component in Bootstrap, which is simple and easy to use. It is very elegant and practical, if you are interested in learning it together, I will introduce you to the pop-up window Component Modal in Bootstrap. This component is simple and easy to use. It is very elegant and practical!

The alert and confirm boxes provided by the browser have poor experience, and the browser does not provide a standard pop-up function to display custom HTML in the form of a dialog box. Therefore, many projects use custom dialog box components. This article introduces how to use bootstrap-based modal components, custom alert, confirm, and modal dialogs in your project. It is relatively simple and practical, and I hope it will be of reference value to you.

1. instance display

For detailed code, you can download the source code through the download link provided earlier. The Code volume is small. The three components add up to more than 200 lines.

If you have javascript component development experience, I believe you can understand this level of code at once. I also provided a demo in the source code, which simulates a scenario that is closer to the actual needs:

1) Click a button on the interface to open the previously defined modal box:

2) You fill in some forms in the opened modal box and click OK to trigger some verification:

When no email is entered:

After entering the email:

These two tips are used to demonstrate the effects of Alert and Confirm. In fact, they may not be so awkward.

3) when the prompt "Password" is blank, the person who is careful will find that the "OK" button is in a disabled state. This is because the "OK" button will eventually complete some asynchronous tasks, before the asynchronous task is completed successfully, I want the modal component to be disabled and the clicked button cannot be clicked repeatedly;

4) I used setTimeout to simulate an asynchronous task. After clicking the OK button, the asynchronous task will be called back for 3 seconds and:

When admin @ admin is entered by email, a prompt is displayed indicating that the submission is successful. After confirmation, all pop-up boxes are closed:

When you enter other values in the email, a message indicating a failed submission is displayed, and the modal box is still displayed:

In the component definition, especially the Registration button, I added some AOP programming processing and used jquery's delayed object to implement the asynchronous programming I needed, for more information, see the source code. If you have any questions, contact us in the comments area.

2. component requirements

Sometimes, in order to write a useful component, you only need to determine its approximate prototype and the interface to be provided externally, and the most important work of writing this component has been completed, encoding has not yet started. For the components to be compiled in this article, the prototype and calling form of the components I want are as follows:

1) custom alert box

The prototype is:

A call requires a maximum of two parameters. One msg is used to pass the prompt content to be displayed, and the other onOk is used to process the callback when the OK button is clicked. The call methods include the following two:

// 1 Alert ('the status of the order you selected does not meet the conditions for the current operation. Please refresh the list and display the latest data before continuing the operation! '); // 2 Alert ({msg:' The order status you selected does not meet the conditions for the current operation. Please refresh the list to display the latest data and continue the operation! ', OnOk: function (){}});

The first is that there is no callback, so you can directly pass msg. The second is that there is a callback, and the options object is used to pass the msg and onOks callback parameters. Whether the onOk callback is available or not, you must close the bullet box when you click the button.

2) custom confirm box

The prototype of this box is only one button different from that of the alert box:

There is only one form of call:

Confirm ({msg: 'The order status you selected does not meet the conditions for the current operation. Please Confirm whether you want to continue the operation! ', OnOk: function () {}, onCancel: function (){}});

OnCancel is the callback when you click the cancel button. Whether the onOk and onCancel Callbacks are available or not, you must close the dialog box when you click the button. OnCancel callback may not exist.

3) custom modal box

Prototype:

Call form:

Var modal = new Modal ({title: '', content:'', width: 600, buttons: [{html :'OK', Selector:'. btn-OK ', callback: function () {// click the callback button}, {html :'Cancel', Selector :'. btn-cancel ', callback: function () {// click the callback of the cancel button}], onContentReady: function () {// Event Callback when modal is added to DOM and Initialization is complete. This callback is only triggered once for each modal instance}, onContentChange: function () {// when modal is called. the setContent method is similar to the Event Callback when the modal content is changed}, onModalShow: function () {// when modal is called. event Callback triggered when modal is displayed in a similar open method}, onModalHide: function () {// when modal is called. hide uses similar methods to hide the Event Callback triggered when modal is used}); $ ('# btn-audit '). click (function () {modal. open ();});

Unlike Alert and Confirm, only one Alert and Confirm instance is required on a page, but multiple Modal instances are required. Therefore, each Modal object must be updated separately. Because the tasks to be completed by every Modal are different, so:

You need a title parameter to set the name to indicate what the Modal is processing;

The content parameter indicates the html content of Modal;

The width parameter sets the width of Modal, while the height of Modal remains auto;

The buttons parameter is used to configure the button above the Modal. Generally, the Modal component only needs two buttons (OK and cancel), but several buttons are required in a few cases, therefore, the button configuration method is more flexible. Each button is configured with three parameters. html indicates the html structure of the button, selector facilitates callback registration through event delegation, and callback when the callback configuration button is clicked;

The onContentReady Event Callback can take the initiative to initialize some html components in the Modal when the Modal Initialization is complete. Because the component Initialization is generally only performed once, it is most appropriate to put it in this callback;

OnContentChange callback is applicable when a Modal needs to be used in different scenarios to display different HTML content, but it is not very useful and the processing logic is slightly complicated, if a Modal instance only does one thing, the onContentChange callback will not be used;

The onModalShow callback is displayed every time the Modal is displayed. Many scenarios are used. For example, if a Modal is used to fill in some form content, you need to reset the form next time to use it, this kind of processing is more appropriate in this callback;

OnModalHide callback is useful, but there are not many scenarios available. It is a reserved interface.

4) Other requirements

All types of bullet boxes are made into virtual mode. A mask is added to the display box;

All frames do not need to be dragged or adjusted in size;

The title of the alert and diert boxes. The number of buttons, button position, and button text are fixed.

Actually:

The modal component of bootstrap supports the mask effect;

Drag and adjust, this function is icing on the cake, but for the software itself, there must be some additional benefits, so I choose not to do this redundant processing;

Alert and dialog do not need to be too personalized. They can unify the style and change the browser's native pop-up experience.

5) call an instance in the DEMO

Next, we will demonstrate how to call these components after completing the development of these three components:

Var modal = new Modal ({title: 'test modal', content: Contents ('your modal-tpl'your .html (), width: 500, onOk: function () {var $ form = this. $ modal. find ('form'); var data = $ form. serializeArray (); var postData ={}; data. forEach (function (obj) {postData [obj. name] = obj. value;}); if (! PostData. email) {Alert ('enter your EMAIL! '); Return false;} var deferred = $. Deferred (); if (! PostData. password) {Confirm ({msg: 'password is empty. Do you want to continue? ', OnOk: function () {_ post () ;}, onCancel: function () {deferred. reject () ;}} else {_ post () ;}return $. when (deferred); function _ post () {// simulate an asynchronous task setTimeout (function () {if (postData. email = 'admin @ admin') {Alert ({msg: 'submitted successfully! ', OnOk: function () {deferred. resolve () ;}} else {Alert ({msg:' submission failed! ', OnOk: function () {deferred. reject () ;}}}}}, 3000) ;}, onModalShow: function () {var $ form = this. $ modal. find ('form'); $ form [0]. reset () ;}}); $ ('# btn-modal '). click (function () {modal. open ();});

3. Implementation points

1) The most basic point is to understand the source code of the modal component of bootstrap:

Initialization Method: $ modal. modal ()

Open: $ modal. modal ('show ')

Close: $ modal. modal (hide)

Event: most events of bootstrap components with transition effects are paired. One is now, and the other is completed, and the modal component defines two pairs:

Show. bs. modal and shown. bs. modal, hide. bs. modal and hidden. bs. modal.

These two pairs of events are triggered before and after the enabled and disabled transitions. For the component requirements that I want to define, show is required when defining components. bs. modal and hidden. bs. the modal events distribute events of the self-defined components when listening to the modal events of bootstrap:

ModalShow and modalHide.

Option:

Backdrop: whether to display the mask;
Keyboard: whether keyboard callback is supported;
Show: whether to display it immediately after Initialization is complete.

The three options are true by default, but I set them to false when I define the components. The keyboard callback feature is not considered for the moment, so it is set to true. When

The pop-up box cannot be displayed immediately when the bootstrap modal Initialization is called, so it cannot be set to true. The reason why backdrop is set to false is described in the next section.

2) mask Processing

If you enable the bootstrap mask, you will find that when you click the mask part, the bullet box will automatically turn off. This is not the expected virtual modal effect, so you must set backdrop to false. However, when this option is set to false, a new problem will occur, that is, the component does not have the mask effect. Therefore, to balance these two issues, you can only write a simple mask for processing:

var $body = $(document.body),BackDrop = (function () {var $backDrop,count = 0,create = function () {$backDrop = $('

').appendTo($body);};return {show: function () {!$backDrop && create();$backDrop[0].style.display = 'block';count++;},hide: function () {count--;if (!count) {$backDrop.remove();$backDrop = undefined;}}}})();

The reason why the count variable is introduced in this Code is that BackDrop is a global singleton object. When the open methods of multiple modal instances are called, the show method of BackDrop is called, to ensure that the BackDrop method is hidden after all modal instances are closed, therefore, a count variable is added to record how many times the show method of BackDrop is called. Only when the count is 0 Can the hide method of BackDrop be called to truly hide BackDrop.

3) default definition of component options

ModalDialog. defaults = {title: '', content:'', width: 600, buttons: [{html :'OK', Selector:'. btn-OK ', callback: getDefaultBtnCallbackProxy ('onok')}, {html :'Cancel', Selector :'. btn-cancel ', callback: getDefaultBtnCallbackProxy ('oncancel')}], onOk: $. noop, onCancel: $. noop, onContentReady: $. noop, onContentChange: $. noop, // callback onModalShow after content replacement: $. noop, onModalHide: $. noop // callback after modal is disabled };

Use buttons to configure two default buttons to confirm and cancel them. Then, to simplify the callback configuration of the two default buttons, extend the interfaces of the two buttons to the previous level, onOk and onCancel will be called when you click OK and cancel, respectively. These two options are completely function callback, unlike onContentReady, which is an Event Callback. GetDefaultBtnCallbackProxy is used to help register onOk and onCancel:

var getDefaultBtnCallbackProxy = function (callbackName) {return function () {var opts = this.options,callback = opts[callbackName] && typeof opts[callbackName] === 'function' ? opts[callbackName] : '';return callback && callback.apply(this, arguments);}}

This will be bound to the modal instance.

4) constructor:

function ModalDialog(options) {this.options = this.getOptions(options);this.$modal = undefined;this.$modalTitle = undefined;this.$modalBody = undefined;this.$modalFooter = undefined;this.state = undefined;}

This mainly declares some instance variables used.

5) Key prototype methods and functions

open: function (state) {this.state = state;!this.$modal && initModal(this, this.options);BackDrop.show();this.$modal.modal('show');}

This is a prototype method, and the initialization of the component is also executed when this method is called (delayed initialization ).

InitModal = function (that, opts) {var $ modal = createModal (that); that. setTitle (opts. title); that. setContent (opts. content); that. addButtons (opts. buttons); that. setWidth (opts. width); bindHandler (that, opts); $ modal. modal (); // call the Modal component $ modal of bootstrap. trigger ('contentready ');}

This is a function used to initialize components. Where:

SetTitle is a prototype method used to set the title of modal;

SetContent is a prototype method used to set the html content of modal;

AddButtons is a prototype method used to register buttons;

SetWidth is a prototype method used to set the width of modal;

BindHandler is a function used to register modal events;

Call $ modal. modal () in the last step to initialize the modal component of bootstrap;

The last step triggers the contentReady event.

BindHandler source code:

bindHandler = function (that, opts) {var $modal = that.$modal;typeof opts.onContentChange === 'function' && $modal.on('contentChange', $.proxy(opts.onContentChange, that));typeof opts.onContentReady === 'function' && $modal.on('contentReady', $.proxy(opts.onContentReady, that));typeof opts.onModalShow === 'function' && $modal.on('modalShow', $.proxy(opts.onModalShow, that));typeof opts.onModalHide === 'function' && $modal.on('modalHide', $.proxy(opts.onModalHide, that));$modal.on('show.bs.modal', function () {$modal.trigger('modalShow');});$modal.on('hidden.bs.modal', function () {$modal.trigger('modalHide');});}

For ease of use, I bound the onContentChange callback context to the current modal instance. The last two event listening Methods encapsulate bootstrap events as my defined modal events.

AddButtons source code:

AddButtons: function (buttons) {var buttons =! $. IsArray (buttons )? []: Buttons, that = this, htmlS = []; buttons. forEach (function (btn) extends htmls.push(btn.html); btn. selector & that. $ modal. on ('click', btn. selector, $. proxy (function (e) {var self = this, $ btn = $ (e. currentTarget); // first disable the button $ btn [0]. disabled = true; var callback = typeof btn. callback = 'function '? Btn. callback: '', ret = callback & callback. apply (self, arguments); if (ret = false) {$ btn [0]. disabled = false; return;} if (typeof (ret) === 'object' & 'done' in ret & typeof ret ['done'] === 'function ') {// the asynchronous task only disables Modalret when the callback is successful. done (function () {that. hide ();}). always (function () {$ btn [0]. disabled = false;});} else {$ btn [0]. disabled = false; that. hide () ;}}, that) ;}); this. $ modalFooter. prepend ($ (htmlS. join ('')));}

The Code shows that:

When a button is clicked, the button is disabled;

When the button returns false, the button is restored, but modal is not closed, indicating that some of the current operations are blocked by the Code;

When the button returns a delayed object, the restore button will wait until the delayed object is completed, and the modal will be disabled only when the delayed object is resolve;

Otherwise, the restore button is automatically disabled.

In this Code, consider:

Button to prevent repeated clicks, modal automatic shutdown, and asynchronous task processing.

6) encapsulate Alert and Confirm

Alert and Confirm are actually a special modal. The other two components can share a modal. After learning about these basics, the components can be defined as follows:

Var Alert, Confirm; (function () {var modal, Proxy = function (isAlert) {return function () {if (arguments. length! = 1) return; var msg = typeof arguments [0] === 'string' & arguments [0] | arguments [0]. msg | '', onOk = typeof arguments [0] === 'object' & typeof arguments [0]. onOk = 'function' & arguments [0]. onOk, onCancel = typeof arguments [0] === 'object' & typeof arguments [0]. onCancel = 'function' & arguments [0]. onCancel, width = typeof arguments [0] === 'object' & arguments [0]. width | 400, _ onModalShow = Function () {this. setWidth (width); this. setContent (msg); this [(isAlert? 'Hide ': 'show') + 'click'] ('. btn-cancel ');}, _ onModalHide = function () {this. setContent ('') ;}; // delayed initialization modalif (! Modal) {modal = new Modal ({'title': 'Operation prompt ', onModalShow: _ onModalShow, onModalHide: _ onModalHide, onContentReady: trim ({'padding-top ': '30px ', 'padding-bottom': '30px '}) }});} else {// If modal has been initialized, you need to re-Listen to the event var $ modal = modal. $ modal; $ modal. off ('modalshow modalHide '); $ modal. off ('modalshow modalHide '); $ modal. on ('modalshow', $. proxy (_ onModalShow, modal); $ modal. on ('modalhide ', $. proxy (_ onModalHide, modal);} modal. setOptions ({onOk: onOk | $. noop, onCancel: onCancel | $. noop}); modal. open () ;}; Alert = Proxy (true); Confirm = Proxy ();})();

In this Code:

First, we consider the delay in initializing the global modal component;

Since the onModalHide and onModalShow Callbacks are event callbacks, the parameters passed in through options during component initialization cannot be changed by modifying options, the callback can only be handled by re-registration. onOk and onCancel are function Callbacks. If you change the references in options, the callback can be changed;

Considering the length of Alert and Confirm content, a new parameter width is added to adjust the width of the box.

4. Summary

This article introduces some methods and practices in defining js components. The code is too many and it is not easy to attract reading interest. However, the method described in this article is relatively simple, in addition, I have used these three components in several projects. Currently, they can solve all the pop-up box requirements I need, so I recommend them, hope to help people in need.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.