Using jquery can I how can i find out when a bootstrap alert is closed?

I want to run some code when a bootstrap alert is closed however, no matter what I try I cannot get it to work.

I need some code that will allow me to know when someone closes the alert box.

Answers 1

  • The problem is you are trying to bind the closed event to the document. The closed event is triggered after the element is detached from the dom tree($parent.detach().trigger('closed.bs.alert').remove()) so it will not get propagated up the dom tree to the document so the handlers attached to document object will not get triggered.

    If you want to use the closed event, you need to bind it to the alert element itself

    $('.alert').on('closed.bs.alert', function(e) {
    
    });
    

    another solution is to use the close event, but it is triggered before the element is removed so there is a possibility that the element removed might be prevented by some handler(by calling event.preventDefault())

    $(document).on('close.bs.alert', '.alert', function(e) {
    });
    

    $('.alert').on('close.bs.alert closed.bs.alert', function(e) {
      snippet.log('alert: ' + e.namespace + '.' + e.type);
    });
    $(document).on('close.bs.alert closed.bs.alert', '.alert', function(e) {
      snippet.log('doc: ' + e.namespace + '.' + e.type);
    });
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet" />
    <br />
    <br />
    <div class="alert alert-danger alert-dismissible fade in" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">?</span>
      </button>
      <h4>Oh snap! You got an error!</h4>
    </div>


Related Articles