confirm-link: An Easy and Elegant Way to Prompt the User to Confirm a Link Click

A simple bit of javascript, but I just wanted to package it up nicely and post it here since I find myself repeatedly going back and looking this up.  Check the links or scroll down if you just want the code.

Source code: github.com/justinmc/confirm-link
Live demo: justinmccandless.com/demos/confirm-link/index.html

 

If you want your users to be presented with a yes/no kind of choice before proceeding, javascript's confirm() function might be a nice simple way to accomplish that.  An alert style box will pop up with two buttons, OK and Cancel, and the result will be passed back to javascript. 

I often use this to make the user verify their choice on things like delete buttons where a simple misclick can have really bad results.  Customization is pretty limited, but if this fits the requirements for you then you can't get much more simple.  Here's the javascript (using jQuery):


 

    
$(document).ready(function () {
    $('a[data-confirm-link]').click(function () {
        if (confirm($(this).data('confirm-link')))
            window.location = $(this).attr('href');
        return false;
    });
});


 

Then, any time you include the data-confirm-link attribute on an <a> tag, the user will be prompted with a confirm box with the text of the attribute.  So the html might look like this:

<a data-confirm-link="Are you sure?  Don't go crying to the webmaster if you delete something you didn't want to." href="delete.html">Delete</a>

 

And there you go, any link you set up like that will automatically prompt the user before following the link.  Hope it helps, I'll probably be coming back to this page myself in the near future.