Mala
Mala

Reputation: 14823

Ajax request on dismissal of twitter bootstrap alerts

I'm using the "alert" functionality from Twitter Bootstrap to display user notifications, like so:

<div class="notification alert alert-info">
 <button type="button" class="close" data-dismiss="alert">&times;</button>
 My message goes here
</div>

These notifications are persistent until the user dismisses them, so when the user clicks the "close" button I would like to fire off an ajax query to the server indicating that the notification should be permanently dismissed.

I'm using jQuery's on() function like so:

$(document).on('click', '.notification .close', function (e) {
    alert('hi!');
    console.log(e);
    e.preventDefault();
});

This works fine, but I'm wondering if there is there a "Bootstrappy" way of doing this?

Upvotes: 1

Views: 2376

Answers (2)

Bob Gregor
Bob Gregor

Reputation: 1161

According to the Bootstrap docs on alerts, I'd bind to the closed or close event, which are custom to Bootstrap.

$(document).on('close', '.alert', function  () 
{
    var id = $(this).data('some_id'); 
    $.get('closed.php?id='+id);
});

there are two events exposed via the API:

  1. close - which is fired immediately
  2. closed - fires after all animations have completed. I'd opt for close - this way you do it immediately and if they navigate / close before the animation completes, it will still be hidden.

The data attribute is to be able to have the server side script differentiate between the alerts. The markup would be:

<div class="alert" data-some_id='foobar'>
    Close me!
</div>

Upvotes: 2

Mariusz Jamro
Mariusz Jamro

Reputation: 31653

In Bootstrap 3.0 you need to use namespaced event name:

$('.alert').bind('closed.bs.alert', function () {
        var id = $(this).data('some_id');
        $.get('closed.php?id='+id);
})

Upvotes: 3

Related Questions