Search code examples
jqueryconfirm

Encapsulate JQuery Confirm into a function


The code below is the sample Jquery Confirm

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    buttons: {
        confirm: function () {
            return true;
        },
        cancel: function () {
            return false
        }
    }
});

This code looks good and it also make me eliminate the JS Confirm. However this code is too many and in-appropriate if all my button has that so I decided to make a function that will call it like this..

function CustomConfirm (message) {
   /* the JS Confirm above */
}

then I will call it just like this

if (CustomConfirm("Are you sure you want to delete?") == true) {
  /* true */
} else {
  /* false */
}

How can I achieve this?


Solution

  • Given how the $.confirm library works you cannot call it in an if condition in the manner you suggest.

    It requires the callback functions for each button to be provided to the settings object when the library is instantiated. In your example it would look like this:

    function CustomConfirm(message, confirmCallback, cancelCallback) {
      $.confirm({
        title: 'Confirm!',
        content: message,
        buttons: {
          confirm: confirmCallback,
          cancel: cancelCallback
        }
      });
    });
    
    CustomConfirm("Are you sure you want to delete?", () => {
      console.log('confirmed...');
    }, () => {
      console.log('cancelled...');
    })