jQuery Confirm Plugin

This plugin displays a confirmation message in place before doing an action. It does not require adding any extra code apart from a call to the plugin itself. One call to $(element).confirm() will do the magic. Also, this plugin doesn't require you to provide a callback function; it figures it out on its own.
You can check the examples for more info.

How does it work?

To put it simply, it saves a copy of all event handlers bound to the element, unbinds them and binds itself instead. A confirmation dialog is displayed when the user triggers the action. If the user chooses to proceed with the action, it rebinds the handlers again and triggers the event. If the user chooses to cancel the action, the dialog disappears.

Docs

$(element).confirm(options)
options
Name Type Optional Description Default Value
msg String Optional Confirmation message 'Are you sure?'
stopAfter string Optional Determines when the confirmation dialog will stop being promoted.
Possible values ('never', 'ok', 'cancel', 'once')
'never'
wrapper String Optional Dialog wrapper '<span></span>'
eventType String Optional The event that triggers the confirmation 'click'
dialogShow String Optional Dialog displaying effect 'show'
dialogSpeed String Optional Dialog displaying speed 'fast'
timeout Integer Optional Time in milliseconds to hide the confirmation dialog 0
options.buttons
ok String Optional Ok caption 'Yes'
cancel String Optional Cancel caption 'No'
wrapper String Optional Button wrapper '<a href="#"></a>'
separator String Optional Separator between buttons '/'
cls String Optional Button class undefined

Examples

First Example

// The action.
$('a').click(function() {
  alert('click');
  return false;
});
 
// The most simple use.
$('a').confirm();

click me!

Second Example

// The action.
$('input[type=button]').click(function() {
  $(this).remove();
});
 
$('input[type=button]').confirm({
  msg:'Do you really want to delete this button?',
  timeout:3000
});

Third Example

// The action.
$('span').mouseover(function() {
  $(this).html('Here is the offer');
});
 
$('span').confirm({
  msg:'See my interesting offer?',
  stopAfter:'ok',
  eventType:'mouseover',
  timeout:3000,
  buttons: {
    ok:'Sure',
    cancel:'No thanks',
    separator:'  '
  }
});

confirmation on mouseover.

Fourth Example

$('a').confirm({
  timeout:3000,
  dialogShow:'fadeIn',
  dialogSpeed:'slow',
  buttons: {
    wrapper:'<button></button>',
    separator:'  '
  }  
});

click me!

AttachmentSize
jquery.confirm-1.2.js3.45 KB
confirm_example.zip21.63 KB

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Question about the jQuery Confirm Plugin

If you attach the confirm plugin to a regular a link, which has the link in the traditional way (in the HTML rather than attached via a jQuery function), can you make sure that link is followed if you click yes on your inline confirm message? It looks like both the yes and no have the "wrapper" default value on them, which means the original link is never followed, and as the original link target link is provided in the HTML, rather than via jquery, I don't see how this will work. I don't want to attach any link targets via jquery, as they are dynamically generated on the page.

Re: Question about the jQuery Confirm Plugin

Can't you just attach a click handler to the links? This can be done in a single line in jQuery.

$('a.example').click(function(event) {
location.href = $(this).attr('href');
}).confirm();

The above code works great. I

The above code works great. I apply a class=delete to my links and style them .delete {background-color:red;color:#fff}

Thank you!

I've got to say... this is quite the nifty plugin! I love it! Thanks so much!

asdfasdfasdfasdf

asdfasdfasdfasdf

Thank you, it's very nice and

Thank you, it's very nice and useful!

Cannot make it work

Sorry, I'm a bit lame... How is it suppossed to work? I'm using jquery 1.2.6 and confirmation-plugin 1.2
I have a link:

Delete...

and finally the code:

jQuery('.confirm').confirm();

But it doesn't do anything, and firebug console complains:

jQuery(".confirm").confirm is not a function
[Break on this error] jQuery('.confirm').confirm();

Are you sure the plugin was

Are you sure the plugin was included properly in your page?
You can send me your example code through the contact form if you want.

Opps, you're right, i had a

Opps, you're right, i had a mistake on the url... thanks, beautiful plugin!!!!!

small extension for moe complex wrappers

Thanks for the nice plugin.

If you want have more than a SPAN around the confirm dialog, for example a DIV-soup for round corners, than it is a good idea instead of

var $dialog = jQuery(option.wrapper).append().append()

to split it into

var $dialog = jQuery(option.wrapper);
$dialog.find(':empty').append().append()...

than you can catch the inner possible parent. perhaps there must be a option to choose between this both behaviors

Trapping body.onUnload event

Ok, here it goes a real challenge. I am trying to use your code to trap the unLoad event, bc I want to add a Confirm window when someone is leaving a website. Beware that leaving a website means type it another url on the browser, press the back button, whatever makes abandon the page. So far, only a pretty raw works exactly as expected. any other jQuery plugin I've been trying out there is not catching the event and the page is just leaving the browser.
Gabriel

Sorry, my raw code seems not

Sorry, my raw code seems not to appear in the blog. Here it goes again:
<body onUnload="alert('leaving so soon')">

My jscript is
$('body').onUnload(function()
{
alert('click');
return false;
});
and my error console gives me "Error: $("body").onUnload is not a function"

My advice for you is to read

My advice for you is to read more about jQuery events
The correct way to do what you intended to do is:
$(window).unload( function () { alert("Bye now!"); });

Can I use it as Javascript

Can I use it as Javascript Confirm Dialog? If so, how? Im new to jquery :(

I need confirm dialog with

I need confirm dialog with yes/no buttons :(

Tried this, but it will not prevent unload on cancel

This code is not working form me with FF3.
//check for formBuilder forms...
$("form").change(function(){
//give alert when data is changed...
$(window).bind('unload',function(e){
e.preventDefault();
if(confirm('Are you sure you want to do this?\nYou changes will be lost...')){
return true;
}else{
return false;
}
});
}).submit(function(){
$(window).unbind('unload');
});
$('form input[type="submit"]').click(function(){
$(window).unbind('unload');
});

Even when I change unload to beforeunload, it will produce a extra popup, do not know why. Any help is welcome ;) Thanx

Well done!

Great plugin. It's very well designed and versatile.

Nice work

This is a pretty amazing little plug-in you came up with. Exactly what I was looking for.

Thanks!

Awesome time saver!

I've been reading tutorials on JQuery, but this was my frist trial. It worked for my application wonderfully. This plugin saved me an hour coding a form confirmation processing page. A talented and beautiful developer, bookmarked!

Great plugin

Great Plugin. Here a suggestion: made a option to choose the location of confirmation instead of replace the button.

Thank you. I'll consider

Thank you. I'll consider extending the plugin in the near future.

Wow!!

So simple to use and an extremely elegant addition to any UI. Thank you!

One minor issue I've noted is that when I click "Yes" (which posts my form), The "Are you sure? Yes/No" vanishes and my original form submit button reappears for the second or two it takes the browser to move to the form action URL. Any thoughts on how to fix that?

Hmm, Maybe if you swap these

Hmm, Maybe if you swap these two lines in the plugin source code:
line 66: $dialog.hide();
line 74: $target.click();
Then the event will be triggered before hiding the dialog.
Please let me know that didn't work.

No, that didn't do it. Even

No, that didn't do it. Even swapping those lines, I think it all still happens so fast relative to the length of time it takes the form to post that it makes no difference to the naked eye.

I think the culprit line of code is whatever shows the original element (the one the plugin is bound to) once the "Yes" confirm is clicked. Stick with that line of thinking, I tried to comment out line 66:

//$target.show();

...but that didn't do it either.

I really like and will

I really like and will include in my new website

Hello, how can I get

Hello, how can I get variables to confirm plugin. I need get there variables message, yes a no because of localization. I just can change this labels directly but can't change it with variables of function from please where is called. Because of my bad english a show example.

//php code

//classic way in lot of languages
function(variable1, variable2, vqariable3);
//but in jquery I don't know how
$('a.delete').click(function() {
alert('click');
return false;
})
$('a.delete').confirm();


Thank you for answer:)

added support for confirming hrefs

wanted support for confirming regular links, so I wrapped the href inside click event if no events available but the href is set.
Great plugin, thanks!

line 46 to 49 becomes:
if (!events && target.href) // No handlers but we have href
{
$target.bind('click',function(){document.location = target.href});
events = jQuery.data(target, 'events');
}
else if (!events)// There are no handlers to save.
return;

Thanks!

This made my day. Please include these lines of code in the original plugin.

Request Downlaod

Great plugin! I like it! I will use it! Thank you very much! ;)

nice to meet you

so good

multi language

I saw it was possible to set button texts. However is it also possible to change the
yes/no link texts. I am using your plugin in DotNetNuke 4 in a multi lingual environment. So Yes/No must be translated.

very nice tutorial.

very nice tutorial. indeed i was looking for a similar solution .
this helped a lot.
Thanks

I am from China,I am a

I am from China,I am a Chinese. My name is HuangShuzhen '黄树振'. Thank you very much!

Ha,Looks like well.Thanks.

Ha,Looks like well.Thanks.

Button wrapper question

First of all, great plugin, thanks for that. I've only got one question - how can I get the following as output for the wrapper?

I have configured the following variables in the button section:


wrapper: '',
cls: 'submit',

With this I get buttons without text in it... :S Any ideas?

Ok, it was a bit early when I

Ok, it was a bit early when I posted my previous post... of course you can't get a correct output when you have to provide both a starting and closing tag, duh!

I've tried to understand how the scripts constructs the output but I can't really figure out how I have to modify it for use with a -tag.

Im struggling to make this

Im struggling to make this work so that the link actually works after the link.button is clicked and confirmed, any help?

Thanks

You may want to have a look

You may want to have a look at this comment:
http://nadiana.com/jquery-confirm-plugin#comment-53
It suggests a change to make this work. I'll consider making link confirmation available in a future release.

Can I move the location of the confirmation text/buttons?

If I have a small icon that users push to launch the confirm plugin when trying to delete something, the icon takes up very little space in my design. I would like the "Are you sure? yes/no" to show up in another place. Is there a way I can specify a target div where this will appear?

also interested on this point

I know you can change the msg from "are you sure?" to "are you sure?". I set the class in the domready function within the msg option.

correction: you can change

correction: you can change "are you sure?"
to

Remove?

Nice plugin :-)

Now I can do facebook-like removal confirmations on mouseover. Thanks!

re: Simple modification

Thought I'd share this. I wanted to be able to specify what element the confirm dialog was inserted before in the DOM, mostly because I'm using this to display a full page confirmation check (like Lightbox, Thickbox, etc...). I added an option "replaceTarget" and then use the existence of this target to specify there the confirm dialog is added.

Here is the replacement code, very little bit adjusted.

jQuery.fn.confirm = function(options) {
options = jQuery.extend({
msg: 'Are you sure?',
stopAfter: 'never',
wrapper: '',
eventType: 'click',
dialogShow: 'show',
dialogSpeed: '',
timeout: 0,
replaceTarget: false,
}, options);
options.stopAfter = options.stopAfter.toLowerCase();
if (!options.stopAfter in ['never', 'once', 'ok', 'cancel']) {
options.stopAfter = 'never';
}
options.buttons = jQuery.extend({
ok: 'Yes',
cancel: 'No',
wrapper:'',
separator: '/'
}, options.buttons);

// Shortcut to eventType.
var type = options.eventType;

return this.each(function() {
var target = this;
var $target = jQuery(target);
var timer;
var saveHandlers = function() {
var events = jQuery.data(target, 'events');
if (!events) {
// There are no handlers to save.
return;
}
target._handlers = new Array();
for (var i in events[type]) {
target._handlers.push(events[type][i]);
}
}

// Create ok button, and bind in to a click handler.
var $ok = jQuery(options.buttons.wrapper)
.append(options.buttons.ok)
.click(function() {
// Check if timeout is set.
if (options.timeout != 0) {
clearTimeout(timer);
}
$target.unbind(type, handler);
$target.show();
$dialog.hide();
// Rebind the saved handlers.
if (target._handlers != undefined) {
jQuery.each(target._handlers, function() {
$target.click(this);
});
}
// Trigger click event.
$target.click();
if (options.stopAfter != 'ok' && options.stopAfter != 'once') {
$target.unbind(type);
// Rebind the confirmation handler.
$target.one(type, handler);
}
return false;
})

var $cancel = jQuery(options.buttons.wrapper).append(options.buttons.cancel).click(function() {
// Check if timeout is set.
if (options.timeout != 0) {
clearTimeout(timer);
}
if (options.stopAfter != 'cancel' && options.stopAfter != 'once') {
$target.one(type, handler);
}
$target.show();
$dialog.hide();
return false;
});

if (options.buttons.cls) {
$ok.addClass(options.buttons.cls);
$cancel.addClass(options.buttons.cls);
}

var $dialog = jQuery(options.wrapper)
.append(options.msg)
.append($ok)
.append(options.buttons.separator)
.append($cancel);

var handler = function() {
//jQuery(this).hide();

// Do this check because of a jQuery bug
if (options.dialogShow != 'show') {
$dialog.hide();
}

if (options.replaceTarget) {
$dialog.insertBefore($('#wrapper'));
}
else {
$dialog.insertBefore(this);
}

// Display the dialog.
$dialog[options.dialogShow](options.dialogSpeed);
if (options.timeout != 0) {
// Set timeout
clearTimeout(timer);
timer = setTimeout(function() {$cancel.click(); $target.one(type, handler);}, options.timeout);
}

return false;
};

saveHandlers();
$target.unbind(type);
target._confirm = handler
target._confirmEvent = type;
$target.one(type, handler);
});
}

Example of use:


// bind a handler to the delete button
$('#delete-group').click(function(){
// enter your click handler here
});

$("#delete-group").confirm({
wrapper: '',
msg:'Do you really want to delete this group?',
// note: the replaceTarget is a jQuery selector, probably best
// if it ends up with a unique result set
replaceTarget: '#wrapper'
});

Hope this helps someone else.

Oops little bug

Oh a stupid bug, just fixed it after I hit submit:


$dialog.insertBefore($('#wrapper'));

should be


$dialog.insertBefore($(options.replaceTarget));

Great work.. one slight bug

Noticed it doesn't work with input buttons when you do the below:

$('input[type=button]').confirm({
msg: 'Confirm: ',
timeout: 3000,
dialogShow: 'fadeIn',
dialogSpeed: 'slow',
buttons: {
wrapper: '',
ok: 'Yes',
cancel: 'No ',
separator: ' / '
}
});

Any change of a fix?

Great plugin good job.

Woops - I should of added

Woops - I should of added that im calling the plugin when inside a javascript function.

function Test() {
$('input[type=button]').confirm({
msg: 'Confirm: ',
timeout: 3000,
dialogShow: 'fadeIn',
dialogSpeed: 'slow',
buttons: {
wrapper: '',
ok: 'Yes',
cancel: 'No ',
separator: ' / '
}
});
}

..html

..html <input type="button"

..html

Look forward to trying it

This could come in handy when combining with Ajax related scripts/forms, particularly validation. Definitely look forward to trying it.
- Brent

nice

nice

Thx

Thx for you Pluging.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options