Summary of experience based on Bootstrap metronic development framework the processing and optimization of "Six" dialog box and Cue box _javascript skills

Source: Internet
Author: User
Tags button type documentation toastr

In various Web development processes, dialog box and prompt box processing is a very common interface processing technology, good use, can give users a good page experience, bootstrap development is also the same, we often add to the page, edit, view the details of the interface using pop-up dialog layer to display data, Deletes may use a prompt confirmation box, if the operation is successful, we can use the richer prompt box to handle, this article mainly compares the technical points which in the bootstrap development uses.

1, the Use of Bootstrap dialog box

The regular bootstrap has several sizes of dialogs, including the default state of the Small dialog box, the Medium width of the dialog box, and the full size of the dialog boxes, Bootstrap dialog box is very friendly, when we use the ESC key or the mouse click the other space, it will automatically hide the dialog box.

They are defined only in class, as the following is the default Small dialog interface code:

<!--------------------------Add/modify information pop-up layer----------------------------> <div id= "Add" class= "Modal Fade" tabindex= "-1" role= "dialog" aria-labelledby= "Mymodallabel" aria-hidden= "true" > <div class= "Modal-dialog" > & Lt;div class= "Modal-content" > <div class= "Modal-header bg-primary" > <button type= "button" class= "Close" data-dismiss= "modal" aria-hidden= "true" ></button> 

The approximate interface is shown below:

Note The dialog style code in the above code, as follows:

<div class= "Modal-dialog" >

If you are a two-size database, you only need to modify here, as shown in the following two codes:

<div class= "Modal-dialog modal-lg" >

And

<div class= "Modal-dialog modal-full" >

Depending on the layout of the interface elements, we can decide which dimensions to use for the dialog-layer definition, but they are called in the same way as the dialog boxes.

The Open dialog box interface looks like this:

Display can select customer
$ ("#btnSelectCustomer"). Show ();

The Close dialog box interface looks like this:

$ ("#add"). Modal ("Hide");

Under normal circumstances, the dialog we pop up is a form that performs a commit operation similar to saving data, so you need to validate the data in the form, and if there are errors, we may need to be alerted on the interface, so when the page is initialized, you need to initialize the form's validation rules. Here is our regular form initialization operation.

Bind-related Event function bindevent () {//Determine whether the form's information is validated by $ ("#ffAdd"). Validate ({meta: "Validate", Errorelement: ' span ', Errorclass: ' Help-block help-block-error ', Focusinvalid:false, highlight:f
        Unction (Element) {$ (Element). Closest ('. Form-group '). addclass (' Has-error ');
          }, success:function (label) {label.closest ('. Form-group '). Removeclass (' Has-error ');
        Label.remove ();
        }, Errorplacement:function (error, Element) {element.parent (' div '). Append (Error);
          Submithandler:function (Form) {$ ("#add"). Modal ("Hide");
          The construction parameter is sent to the background var postdata = $ ("#ffAdd"). Serializearray ();
            $.post (URL, postdata, function (JSON) {var data = $.parsejson (JSON); if (data.
              Success) {//Add image upload processing $ (' #file-portrait '). Fileinput (' upload ');
              Save Success 1. Close the pop-up layer, 2. Refresh table DataShowtips ("Save Success");
            Refresh (); else {ShowError (save failed: + data.)
            ErrorMessage, 3000); }). Error (function () {showtips () you are not authorized to use this feature, please contact your administrator for processing.
          ");
        });
    }
      }); }

But generally the code repeats a lot, so we can encapsulate the function, reuse some of the code, and use more concise processing code, but we can do the same.

 Bind related event
    function bindevent () {
      //Add, edit the form processing
      formvalidate ("Ffadd", function (form) {
        $ ("#add"). Modal ("Hide");
        The construction parameter is sent to
        the background var postdata = $ ("#ffAdd"). Serializearray ();
        $.post (URL, postdata, function (JSON) {
          var data = $.parsejson (JSON);
          if (data. Success) {
            //Save Success 1. Close the pop-up layer, 2. Refresh the table data
            showtips ("Save Success");
            Refresh ();
          }
          else {
            ShowError ("Save failed:" + data.) ErrorMessage, 3000);
          }
        ). Error (function () {
          showtips ("You are not authorized to use this feature, please contact your administrator for processing.") ");
        });
      });
    

2, delete the confirmation of the dialog box processing

1) The use of Bootbox plug-ins

In addition to the general dialog above, we often encounter a simple confirmation dialog box, although you can use the above code to build a confirmation dialog box, but generally do not need such trouble, you can use the Plug-in Bootbox confirmation dialog box to handle.

Bootbox.js is a small JavaScript library that helps you quickly create a dialog box when using the bootstrap framework, or it can help you create, manage, or delete any required DOM elements or JS event handlers.

Bootbox.js uses a three-way design to mimic some of their native JavaScript methods. Their exact method of signature is flexible each can take various parameters to customize the label and specify default values, but they are usually called the same:

Bootbox.alert (message, callback)

BOOTBOX.PROMPT (message, callback)

BOOTBOX.CONFIRM (message, callback)

The only parameter required is alert is message; Callback is a required confirm and prompt call to determine the user's response. Even when calling the alert callback is OK when the user dismisses the dialog box because our packaging method cannot be useful for a block like their native language: they are asynchronous rather than synchronized.

These three methods call One-fourth public methods, and you can also use your own custom dialog box to create:

Bootbox.dialog (Options)

More API Help documentation see: http://bootboxjs.com/documentation.html

Alert

Bootbox.alert ("Hello world!", function () {
example.show ("Hello World Callback");

Confirm

Bootbox.confirm ("Are you sure?", function (Result) {
example.show ("Confirm result:" +result);
});

or code:

 Bootbox.confirm (Are you sure you want to delete the selected records?) ", function (Result) {
          if (result) {
            //finally remove the last comma,
            ids = ids.substring (0, ids.length-1);
            Then send the information of the asynchronous request to the background to delete the data
            var postdata = {Ids:ids};
            $.get ("/province/deletebyids", PostData, function (JSON) {
              var data = $.parsejson (JSON);
              if (data. Success) {
                showtips ("Delete selected record succeeded");
                Refresh ()//Flush page Data
              }
              else {
                showtips. errormessage);}});
        

Prompt

Bootbox.prompt (' What is your name? ', function (result) {
if (result = = null) {
  example.show ("prompt dismissed");
else {
  example.show ("Hi <b>" +result+ "</b>");
}
);

Custom Dialog

Use the code and Interface effects as follows:

Bootbox.dialog (...)

[2)

2) The use of Sweetalert plug-ins

Although the above effect is very consistent with the bootstrap style, but the interface is slightly monotonous. The above effect is not that I like this style, I encountered a look more beautiful effect, as shown below.

This effect is implemented by introducing plug-in Sweetalert (http://t4t5.github.io/sweetalert/).

 Swal ({
    title: "Action hint",
    text:newtips,
    type: "Warning", Showcancelbutton:true,
    Confirmbuttoncolor: "#DD6B55",
    cancelbuttontext: "Cancel",
    confirmbuttontext: "Yes, perform the deletion!" ",
    closeonconfirm:true
  }, function () {
    delfunction ();
  });

The above interface effect is similar to the implementation code shown below:

In general, its pop-up code can be done very simply, as shown below.

3, the Information prompt box processing

Both of the above processing, are implemented using pop-up dialog box, and the interface is blocked, in general, we do information prompts effect, hope it does not affect our further operations, or at least provide a very short automatic vanishing effect.

So here we will introduce the next jnotify plug-ins and Toastr plug-ins.

1) The use of Jnotify prompt box

jnotify prompt box, a good jquery results balloon plugin. After submitting the form, we return the results via AJAX response backstage and display the return information in the foreground, jnotify can display the operation result information very elegantly. Jnotify is a jquery based information Tip plug-in that supports three of informational prompts for operational success, failure of operations, and Operation reminders. Jnotify browser compatibility is very good, support changes to the content, support positioning the location of the cue box, you can configure plug-in parameters.

Jsuccess (Message,{option});
Jerror ("The operation failed, please retry!!");
Jnotify ("Note: Please improve your <strong> profile!") </strong> ");

Jnotify Parameter Detail configuration:

Autohide:true,//        whether to automatically hide the cue bar
Clickoverlay:false,//whether to click the      mask layer to turn off the cue bar
minwidth:200,          //min width
timeshown:1500,         //Display time: Milliseconds
showtimeeffect:200,       //time required to display on the page: Ms
hidetimeeffect:200,       // The time required to disappear from the page: milliseconds
longtrip:15,          //When the cue bar is displayed and hidden the displacement
horizontalposition: "Right",   //Horizontal position: Left, center, Right
verticalposition: "Bottom",   //Vertical position: Top, center, bottom
showoverlay:true,//        show Mask Layer
coloroverlay: "#000",//      set matte layer color
opacityoverlay:0.3,//      set matte layer transparency
ONCLOSED:FN      // After you close the prompt box to execute the function, you can invoke the other jnotify again. Call as three of the above.

Here is a list of the hungry common methods I encapsulate inside the script class to display the hint effect.

Display error or hint information (need to refer to jnotify related file)
function ShowError (tips, Timeshown, autohide) {
  jerror (
   tips,
   {
     Autohide:autohide | | True,//added in v2.0
     Timeshown:timeshown | | 1500,
     horizontalposition: ' Center ',
     verticalposition: ' Top ',
     Showoverlay:true,
     Coloroverlay: ' #000 ',
     oncompleted:function () {//Added in v2.0
       //alert (' jnofity is completed! ');
     }
   }
  );
}
Display prompt information
function showtips (tips, Timeshown, autohide) {
  jsuccess (
   tips,
   {
     autohide: AutoHide | | True,//added in v2.0
     Timeshown:timeshown | | 1500,
     horizontalposition: ' Center ',
     verticalposition: ' Top ',
     showoverlay:true,
     coloroverlay: ' #000 ',
     oncompleted:function () {//Added in v2.0
       //alert ( ' Jnofity is completed! ');
     }

So when we use the Ajax post method, we can be prompted according to different needs.

  var postdata = $ ("#ffAdd"). Serializearray ();
          $.post (URL, postdata, function (JSON) {
            var data = $.parsejson (JSON);
            if (data. Success) {
              //Add image upload processing
              $ (' #file-portrait '). Fileinput (' upload ');
              Save Success 1. Close the pop-up layer, 2. Refresh the table data
              showtips ("Save Success");
              Refresh ();
            }
            else {
              ShowError ("Save failed:" + data.) ErrorMessage, 3000);
            }
          ). Error (function () {
            showtips ("You are not authorized to use this feature, please contact your administrator for processing.") ");
          });

2) The use of Toastr plug-ins

Toastr is a JavaScript library used to create Gnome/growl-style, non-blocking page message reminders. , TOASTR can be set four kinds of notification mode: Success, error, warning, prompt, and prompt window position, animation effect can be set by the number, in the official station can be checked parameters to generate JS, very convenient to use.

The plugin address is: http://codeseven.github.io/toastr/

It can create the following effects: Warning, danger, Success, prompt dialog box information, as shown below.

Its use of the JS code is shown below.

Displays a warning with no title
toastr.warning (' My name is Inigo Montoya. Killed my father, prepare to die! ')
Show a success, title
toastr.success (' Have fun storming the castle! ', ' Miracle Max Says ')
//Show Error title
Toastr.error (' I Do does not have the word means what you it means. ', ' inconceivable! '
Clear the current list

The parameter definitions for this plug-in are shown below.

Parameter settings, if the default value can be omitted with the following generation
  toastr.options = {
    "CloseButton": false,//whether to show the Close button
    "Debug": false,//whether to use the debug mode "
    positionclass": "Toast-top-full-width",//pop-up window position
    "showduration": "300",//Show animation time
    "Hideduration": "1000",//Disappeared animation time
    "TimeOut": "5000",//Show Time
    "ExtendedTimeout": "1000",//Long Show Time
    "showeasing": "Swing" ,//Display animation buffering mode
    "hideeasing": "Linear",//disappear when the animation buffering mode
    "Showmethod": "FadeIn",//Display animation mode
    "Hidemethod": "Fadeout"//Vanishing Animation mode
    };
    Successfully prompted to bind
    $ ("#success"). Click (function () {
    toastr.success ("Congratulations on your Success");
    }

Above is I in the project, to dialog box and the Prompt box processing and the Optimization experience summary, hoped for everybody learns to improve the Web interface to be helpful. If you want to know more information, please pay attention to cloud Habitat community website!

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.