JQUERY-CONFIRM

alerts, confirms and dialogs in one.

Welcome to jquery-confirm!

Easy to use and highly flexible!
A jQuery plugin that provides great set of features like, Auto-close, Ajax-loading, Themes, Animations and more.
This plugin is actively developed, I would love you have your suggestions.

Please post your Suggestions here.

Features

These features can practically be used like so.

Elegant Alerts.

Stacked Confirmations

Need input?

Its also a Dialog.

Not so important modal

Loading from remote places

Some actions maybe critical

Responds to keystrokes

Automatically centered

Loading images

Clean animations

Getting started

Installation

Download
Download the Latest version and use files in the /dist/ folder.

via Bower:
$ bower install craftpip/jquery-confirm

via Npm:
$ npm install jquery-confirm

Dependencies:

  • Bootstrap by Twitter >= v3
  • jQuery library > v1.8

Quick Usage

$.alert

adds one button (okay) if no buttons are specified, this lets the user to close the modal.

$.alert({
    title: 'Alert!',
    content: 'Simple alert!',
});

$.confirm

if no buttons are specified, two buttons (Okay & cancel) will be added.

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    buttons: {
        confirm: function () {
            $.alert('Confirmed!');
        },
        cancel: function () {
            $.alert('Canceled!');
        },
        somethingElse: {
            text: 'Something else',
            btnClass: 'btn-primary',
            keys: ['enter', 'shift'],
            action: function(){
                $.alert('Something else?');
            }
        }
    }
});
                                

$.dialog

removes buttons and explicitly shows the closeIcon (×)

$.dialog({
    title: 'Text content!',
    content: 'Simple modal!',
});

$.fn.confirm

This can be used to bind to a element directly
If no buttons are defined, the default buttons (okay and cancel) will be added, and default action for okay will be to redirect on the given href. use this.$target to get the clicked element.

Goto twitter

HTML
<a class="twitter" data-title="Goto twitter?" href="http://twitter.com/craftpip">Goto twitter</a>
Javascript
$('a.twitter').confirm({
    content: "...",
});
$('a.twitter').confirm({
    buttons: {
        hey: function(){
            location.href = this.$target.attr('href');
        }
    }
});

Shorthand usage

The shorthand thingy takes in two string arguments, first one is the content of the dialog and second the title of the dialog. The second argument is optional.

$.alert('Content here', 'Title here'); try me
$.confirm('A message', 'Title is optional'); try me
$.dialog('Just to let you know'); try me

NOTE : The $.confirm(), $.dialog() & $.alert() methods are alias of jconfirm().
All three methods indirectly call the jconfirm base function altering the provided options.

ADVANCED: this.$body is the body div for jquery-confirm. You can find and alter any element at run time.

Buttons

Its all what you need to know about buttons in jquery-confirm v3.
Defining multiple buttons is introduced in v3.

You can access the button element via this.$$heyThere for heyThere button in the below snippet.
this is to change the button properties at run time.

Definition

Buttons can be defined in the following fashion, pretty self explanatory.

$.confirm({
    buttons: {
        hello: function(){
            // button action
        },
        hey: function(){
            this.$$hello.trigger('click'); // click the other button
            this.buttons.hello.setText('Helloooo'); // do whatever

            this.$$hey.prop('disabled', true); // disable the current button
            // or
            this.buttons.hey.disable();
        },
        heyThere: {
            text: 'Hey there!',
            btnClass: 'btn-primary',
            keys: ['enter', 'a'],
            action: function(){
                // button action.
            }
        },
    }
});

Button text

$.confirm({
    buttons: {
        something: function(){
            // here the key 'something' will be used as the text.
            $.alert('You clicked on something.');
        },
        somethingElse: {
            text: 'Something else &*', // Some Non-Alphanumeric characters
            action: function(){
                $.alert('You clicked on something else');
            }
        }
    }
});

Button style

Simply applying classes to buttons.

Available bootstrap options are btn-primary btn-inverse btn-warning btn-info btn-danger btn-success or any other class name.

$.confirm({
    buttons: {
        info: {
            btnClass: 'btn-info',
            action: function(){}
        },
        danger: {
            btnClass: 'btn-danger any-other-class', // multiple classes.
            ...
        },
        warning: {
            btnClass: 'btn-warning',
            ...
        },
    }
});

Button keys

Listen to keyup events for individual buttons. A button can listen for multiple keys at a time.

Available options are:
a to Z, tilde, enter, shift, tab, capslock, ctrl, win, alt, esc, space.
$.confirm({
    buttons: {
        specialKey: {
            text: 'On behalf of shift',
            keys: ['shift', 'alt'],
            action: function(){
                $.alert('Shift or Alt was pressed');
            }
        },
        alphabet: {
            text: 'A, B',
            keys: ['a', 'b'],
            action: function(){
                $.alert('A or B was pressed');
            }
        }
    }
});

In this example, the YES button is hidden using bootstrap's hide class, thus the user can only use keys to proceed.

$.confirm({
    title: false,
    content: 'A very very critical action here! <br> ' +
             'the proceed button is hidden.' +
             'The only way to proceed is to press the key <strong>Y</strong>.<br>' +
             'Press <span style="font-size: 20px;">Y</span> to proceed.',
    buttons: {
        yes: {
            btnClass: 'hide', // hide is a bootstrap class to hide elements
            keys: ['y'],
            action: function () {
                $.alert('Critical action <strong>was performed</strong>.');
            }
        },
        no: {
            keys: ['N'],
            action: function () {
                $.alert('You clicked No.');
            }
        },
    }
});

Button functions

Button functions provide a nice and clean way to alter your buttons in run-time.
if this is not enough you can use this.$$<buttonName> to get the DOM element

$.confirm({
    buttons: {
       buttonA: {
            text: 'button a',
            action: function () {
                this.buttons.buttonB.setText('Changed it!');
                return false;
            }
        },
        buttonB: {
            text: 'button b',
            action: function () {
                this.buttons.buttonA.disable();
                return false;
            }
        },
        reset: function () {
            this.buttons.buttonA.enable();
            this.buttons.buttonB.setText('button b');
            return false;
        }
    }
});

A full list of functions for buttons.

Function Code Description
setText this.buttons.<buttonName>.setText(text) The text you want to set.
addClass this.buttons.<buttonName>.addClass(className) Add a class to the button
removeClass this.buttons.<buttonName>.removeClass(className) remove a class to the button
disable this.buttons.<buttonName>.disable() Disable the button
enable this.buttons.<buttonName>.enable() Enable the button
show this.buttons.<buttonName>.show() Show the button via CSS
hide this.buttons.<buttonName>.hide() Hide the button via CSS

Customizing

Custom width

Jquery-confirm uses bootstrap's grid system for its layout.
You can simply provide column classes to adjust the modal's width.

You can also set responsive layouts. Bootstrap grid docs

instead of typing the whole thing, provide keywords like
xlarge/xl equivalent to col-md-12
large/l equivalent to col-md-8 col-md-offset-2
medium/m equivalent to col-md-6 col-md-offset-3
small/s equivalent to col-md-4 col-md-offset-4
xsmall/xs equivalent to col-md-2 col-md-offset-5

$.confirm({
    columnClass: 'small'
});
$.confirm({
    columnClass: 'col-md-4'
});
$.confirm({
    columnClass: 'col-md-4 col-md-offset-8 col-xs-4 col-xs-offset-8'
});
$.confirm({
    columnClass: 'col-md-4 col-md-offset-8 col-xs-4 col-xs-offset-8',
    containerFluid: true, // this will add 'container-fluid' instead of 'container'
});

Icons

Give meaning to your dialog with custom icons.
Read about Font Awesome here .

$.confirm({
    icon: 'glyphicon glyphicon-heart',
    title: 'glyphicon'
});
$.confirm({
    icon: 'fa fa-warning',
    title: 'font-awesome'
});
$.confirm({
    icon: 'fa fa-spinner fa-spin',
    title: 'Working!',
    content: 'Sit back, we are processing your request!'
});

Close icon

jQuery confirm uses &times; html entity for this close symbol, however you can use Any icon of your choice (fa, glyphicon, zmdi)

By default closeIcon is set to null. That means, if buttons are not defined the closeIcon will be shown, else will not be shown.
To explicitly show closeIcon set it to a truthy value and vise versa.

Turn on closeIcon explicitly

$.confirm({
    closeIcon: true
});

Using other libraries for icons

$.confirm({
    closeIcon: true,
    closeIconClass: 'fa fa-close'
});

Handle closeIcon's callback

Control what happens when close icon is clicked.
closeIcon can take in function to handle the button click or you can return a button name.

$.confirm({
    closeIcon: function(){
        return false; // to prevent close the modal.
        // or
        return 'aRandomButton'; // set a button handler, 'aRandomButton' prevents close.
    },
    // or
    closeIcon: 'aRandomButton', // set a button handler
    buttons: {
        aRandomButton: function(){
            $.alert('A random button is called, and i prevent closing the modal');
            return false; // you shall not pass
        },
        close: function(){
        }
    }
});

Ajax loading

With jconfirm you have the power to load content directly when needed via ajax, no extra code.
Two methods are available to load content via Ajax:

  1. Pass in String content the URL with "URL:" prepended.
    content: "URL:http://example.com/getData?id=1"
  2. Pass in Function that returns a jQuery ajax promise.
    content: function(){ return $.get(...); }
From v3 onwards, buttons are not disabled until ajax call is complete.
contentLoaded is called when the ajax is complete. before the content is put in DOM.

Using the "URL:" prefix

Using the url prefix is the quick way, however has some limitations like you cannot modify the ajax call's method, dataType, etc.
To use, prepend your URL with "URL:" ends up like "URL:http://example.com/file.extension".

NOTE: the returned data is set as content automatically before contentLoaded callback is called.

view text.txt
$.confirm({
    content: 'url:text.txt',
    title: 'Title',
});

Using Ajax promise

This option provides full control over the ajax options and what data is to be inserted. The content takes a function that returns a jQuery promise ($.ajax, $.get, $.post, etc.). In this example a json object is requested, and a part of it is set as content.

NOTE: the returned data is NOT set as content automatically, you must set the content yourself.

view bower.json
$.confirm({
    content: function () {
        var self = this;
        return $.ajax({
            url: 'bower.json',
            dataType: 'json',
            method: 'get'
        }).done(function (response) {
            self.setContent('Description: ' + response.description);
            self.setContentAppend('<br>Version: ' + response.version);
            self.setTitle(response.name);
        }).fail(function(){
            self.setContent('Something went wrong.');
        });
    }
});

Ajax complete callback contentLoaded

When the ajax call is complete the contentLoaded function is called with arguments Data, Status & Xhr object.
contentLoaded is called before the content is put in DOM
If you want to do stuff after the content has put in DOM, use onContentReady

$.confirm({
    content: 'url:text.txt',
    contentLoaded: function(data, status, xhr){
        // data is already set in content
        this.setContentAppend('<br>Status: ' + status);
    }
});

Using the url: prefix method

$.confirm({
    content: function(){
        var self = this;
        self.setContent('Checking callback flow');
        return $.ajax({
            url: 'bower.json',
            dataType: 'json',
            method: 'get'
        }).done(function (response) {
            self.setContentAppend('<br>Done!');
        }).fail(function(){
            self.setContentAppend('<br>Fail!');
        }).always(function(){
            self.setContentAppend('<br>Always!');
        });
    },
    contentLoaded: function(data, status, xhr){
        self.setContentAppend('<br>Content loaded!');
    },
    onContentReady: function(){
        this.setContentAppend('<br>Content ready!');
    }
});

Using the Ajax promise method

You can set your content in any of the callbacks. callback execution flow:

  1. Promise's done
  2. Promise's always
  3. contentLoaded
  4. onContentReady

Auto close

Do a action if the user does not respond within the specified time.
This comes in handly when the user is about to do something critical.
The autoClose option takes in a string, like 'confirm|4000' where confirm is the action to trigger after 4000 milliseconds.
Practical examples of autoClose

$.confirm({
    title: 'Delete user?',
    content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
    autoClose: 'cancelAction|8000',
    buttons: {
        deleteUser: {
            text: 'delete user',
            action: function () {
                $.alert('Deleted the user!');
            }
        },
        cancelAction: function () {
            $.alert('action is canceled');
        }
    }
});
$.confirm({
   title: 'Logout?',
    content: 'Your time is out, you will be automatically logged out in 10 seconds.',
    autoClose: 'logoutUser|10000',
    buttons: {
        logoutUser: {
            text: 'logout myself',
            action: function () {
                $.alert('The user was logged out');
            }
        },
        cancel: function () {
            $.alert('canceled');
        }
    }
});

Background dismiss

Control what happens if the user clicks outside the modal.

backgroundDismiss is set to false by default.
$.confirm({
    backgroundDismiss: true, // this will just close the modal
});
$.confirm({
    backgroundDismiss: function(){
        return false; // modal wont close.
    },
});
$.confirm({
    backgroundDismiss: function(){
        return 'buttonName'; // the button will handle it
    },
});
$.confirm({
    backgroundDismiss: 'buttonName',
    content: 'in here the backgroundDismiss action is handled by buttonName' +
    '<div class="checkbox"><label><input type="checkbox" id="enableCheckbox"> Enable backgroundDismiss</label></div>',
    buttons: {
        buttonName: function () {
            var $checkbox = this.$content.find('#enableCheckbox');
            return $checkbox.prop('checked');
        },
        close: function () {
        }
    }
});

Background dismiss animation

Fancy animations to grab users attention. Click outside the modal to see the animation.

$.confirm({
    backgroundDismiss: false,
    backgroundDismissAnimation: 'shake',
});
$.confirm({
    backgroundDismiss: false,
    backgroundDismissAnimation: 'glow',
});

Escape key

Control what happens when the escape key is pressed. This is enabled by default.
backgroundDismiss is called when escape key is pressed. if backgroundDismiss is false, it will shake the modal.

$.confirm({
    escapeKey: true,
    backgroundDismiss: false,
});
$.confirm({
    escapeKey: 'buttonName',
    buttons: {
        buttonName: function(){
            $.alert('Button name was called');
        },
        close: function(){

        }
    }
});

RTL support

If you need to show the confirm box in rtl then you should set the rtl option to true.

$.alert({
    title: 'پیغام',
    content: 'این یک متن به زبان شیرین فارسی است',
    confirmButtonClass: 'btn-primary',
    rtl: true,
    closeIcon: true,
    buttons: {
        confirm: {
            text: 'تایید',
            btnClass: 'btn-primary',
            action: function () {
                alert('تایید شد.');
            }
        },
        cancel: {
            text: 'انصراف',
            action: function () {

            }
        }
    }
});

Callbacks

Get more control over the modal, mainly important for binding events for the modal elements.
contentLoaded callback is called when Ajax loading is used

$.confirm({
    title: false,
    content: 'url:callback.html',
    onContentReady: function () {
        // when content is fetched & rendered in DOM
        alert('onContentReady');
        var self = this;
        this.buttons.ok.disable();
        this.$content.find('.btn').click(function(){
            self.$content.find('input').val('Chuck norris');
            self.buttons.ok.enable();
        });
    },
    contentLoaded: function(data, status, xhr){
        // when content is fetched
        alert('contentLoaded: ' + status);
    },
    onOpenBefore: function () {
        // before the modal is displayed.
        alert('onOpenBefore');
    },
    onOpen: function () {
        // after the modal is displayed.
        alert('onOpen');
    },
    onClose: function () {
        // before the modal is hidden.
        alert('onClose');
    },
    onDestroy: function () {
        // when the modal is removed from DOM
        alert('onDestroy');
    },
    onAction: function (btnName) {
        // when a button is clicked, with the button name
        alert('onAction: ' + btnName);
    },
    buttons: {
        ok: function(){

        }
    }
});

Global defaults

You can setup global settings for your jconfirm.

jconfirm.defaults should be set after the plugin has loaded. of course.

jconfirm.defaults = {
    title: 'Hello',
    content: 'Are you sure to continue?',
    buttons: {},
    defaultButtons: {
        ok: {
            action: function () {
            }
        },
        close: {
            action: function () {
            }
        },
    },
    contentLoaded: function(data, status, xhr){
    },
    icon: '',
    bgOpacity: null,
    theme: 'white',
    animation: 'zoom',
    closeAnimation: 'scale',
    animationSpeed: 400,
    animationBounce: 1.2,
    rtl: false,
    container: 'body',
    containerFluid: false,
    backgroundDismiss: false,
    backgroundDismissAnimation: 'shake',
    autoClose: false,
    closeIcon: null,
    closeIconClass: false,
    columnClass: 'col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1',
    onContentReady: function () {},
    onOpenBefore: function () {},
    onOpen: function () {},
    onClose: function () {},
    onDestroy: function () {},
    onAction: function () {}
};

Options

Options, their defaults, possibilities and explainations.

Name Type Default Description
title String, Function 'Hello' Title of the dialog.
Also accepts a function that returns a string.
content String, Function 'Are you sure to continue?' Content for the dialog.
Accepts functions that return string or ajax promise.
contentLoaded Function function(data,status,xhr){} In use only when content is loaded via Ajax. is called on always callback of $.ajax
icon String '' Icon class prepended before the title. ex: 'fa fa-icon'
bgOpacity Float null if null, the theme's default bg opacity is applied.
theme String 'light' Color theme for the dialog.
possible options are 'light', 'dark', 'material' & 'bootstrap'
animation String 'zoom' The Open animation for the dialog.
possible options are right, left, bottom, top, rotate, none, opacity, scale, zoom, scaleY, scaleX, rotateY, rotateYR (reverse), rotateX, rotateXR (reverse)
The 'blur' animation was removed in v1.1.2
closeAnimation String 'scale' The close animation for the dialog. Same options as animation.
animationSpeed Number 500 Animation duration in milliseconds.
animationBounce Float 1.2 Adds a Bounce open animation,
1 = No bounce
escapeKey Boolean, String false if false, escapeKey wont work,
if true, will work, but no callbacks,
if string, will be assigned to button.
rtl Boolean false Use the Right to left text layout.
container String 'body' Specify where the generated HTML content for jconfirm should append.
By default it appends in the document's <body>.
containerFluid Boolean false If true, will use the container-fluid layout, to use the full browser width.
backgroundDismiss Boolean, String, Function false If false, user wont be able to exit by clicking out.
If true, user will be able to click out, no callback.
If string, will be assigned to button.
If function, will be used as callback.
backgroundDismissAnimation String 'shake' Animation to perform to grab the user's attention when user clicks out of the box.
autoClose String false Auto-close the dialog within a specified time, if the user doesn't respond.
possible option 'buttonName|400'

the string is divided in two halves with pipe '|', the first part specifies the button name to trigger. The other half specifies the wait time in milliseconds.

closeIcon Boolean null By default closeIcon is visible if both buttons are false. (dialog mode).
closeIcon can be shown by setting this value to true.
closeIconClass String false By default jQuery confirm uses × html entity for this close symbol. You can provide icon class here to change it.
columnClass String 'col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1' Provides a better way to set Custom width and is responsive.
You can also set custom widths for different display sizes using the Bootstraps grid.
onContentReady Function function(){} is called when the content is put in DOM and the modal is open. (When the modal is completed ready.)
onOpenBefore Function function(){} is called when the modal is going to be opened.
onOpen Function function(){} is called when the modal has finished opening.
onClose Function function(){} is called when the modal is going to be closed.
onDestroy Function function(){} is called after the modal element is removed from the DOM.
onAction Function function(buttonName){} is called when any of the button is clicked. buttonName is provided as argument.
watchInterval Number 100 Watch the modal for changes and is centered on screen.
Added in v 2.5.0

Api

These are a few stuff, that will let you interact and make changes in your modal on run time.
The function $.confirm() returns an object on execution.

var jc = $.confirm({
    title: 'awesome',
    onContentReady: function(){
        // this === jc
    }
});

jc.setTitle(string)

function

Sets the title and overwrites jc.title

jc.setContent(string)

function

Sets the content and overwrites jc.content

jc.setContentPrepend(string)

function

Prepends content to content.

jc.setContentAppend(string)

function

Appends content to content

jc.<buttonName>.setText(text)

function

Set text for a button

jc.<buttonName>.addClass(text)

function

Adds a class to the button

jc.<buttonName>.removeClass(text)

function

Removes class from the button

jc.<buttonName>.disable()

function

Disabled the button with attribute disabled='disabled'

jc.<buttonName>.enable()

function

Enables a previously disabled button

jc.<buttonName>.hide()

function

Hides the button using CSS 'display: none'

jc.<buttonName>.show()

function

Shows a previously hidden button

jc.setIcon(iconClass)

function

Sets the icon and overwrites jc.icon

jc.close()

function

The close method closes/destroys the dialog.

jc.open()

function

Opens the modal again, if it is closed. (Added in v3.0.0)

jc.isClosed()

function

returns true if the modal is closed, else false.

jc.isOpen()

function

returns true if the modal is open, else false.

jc.setDialogCenter()

function

Centers the dialog on screen. This is done for you by the watch timer when the content changes.

jc.$body

jquery DOM element

Alias: jc.$b, is the modal body that includes buttons content title and stuff.

jc.$content

jquery DOM element

You can access your Dialogs contents via this object.

jc.$title

jquery DOM element

To access the title DOM of the modal. same use as with $content

jc.$icon

jquery DOM element

To access the icon DOM of the modal. same use as with $content

jc.$target

jquery DOM element

To access the clicked element, only available when using $(element).confirm() and using a confirm callback.