Nicer warning dialogs with Rails and Bootstrap

Ruby on Rails has a very convenient way of presenting a dialog for potentially dangerous tasks that require some confirmation before proceeding. All you have to do is add

data: {confirm: "Are you sure?"}

A problem with those, though, is that most (all?) browsers make the dialogs quite ugly:

Call to Buzz - ugly dialog

For Call to Buzz, I wanted to finally have something better. Thankfully, there’s a very simple solution, as long as you are using Bootstrap: Twitter::Bootstrap::Rails::Confirm. You just add it to your project and the dialog now looks like this:

Call to Buzz - bootstrap dialog

That looks much better, but it’d be nice if it had a nice title, better matching buttons, etc. It’s easy to do by adding some data attributes to the link and the documentation for this gem recommends creating a new method to use instead of link_to when deleting something. I wasn’t very happy with this approach so I resolved it with pure JavaScript so my links remain oblivious to the fact that I’m using this gem:

$(document).ready(function () {
  $("a[data-confirm]").data({
    "confirm-fade": true,
    "confirm-title": "Call to Buzz"
  });
  $("a[data-method=delete]").data({
    "confirm-title": "Warning",
    "confirm-cancel": "Cancel",
    "confirm-cancel-class": "btn-cancel",
    "confirm-proceed": "Delete",
    "confirm-proceed-class": "btn-danger"
  });
});

And with that, the dialog now looks like this:

Call to Buzz - much better bootstrap dialog

Update: Later on I wanted to be able to define some extra parameters on a link, such as:

data: {confirm: "Are you sure you want to disconnect?", confirm_proceed: "Disconnect"}

To achieve that I re-wrote the code that dynamically adds the extra confirm parameters to look like this (this uses jQuery 3, on earlier version you’d have to do confirm-fade instead of confirmFade):

$("a[data-confirm]").each(function (_, link) {
    var $link = $(link);
    var data = $link.data();
    data = $.extend({}, {
        "confirmFade": true,
        "confirmTitle": "Call to Buzz"
    }, data);
    if ($link.data("method") == "delete") {
        data = $.extend({}, {
            "confirmTitle": "Warning",
            "confirmCancel": "Cancel",
            "confirmCancelClass": "btn-cancel",
            "confirmProceed": "Delete",
            "confirmProceedClass": "btn-danger"
        }, data);

    }
    $link.data(data);
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s