[javascript] Twitter Bootstrap alert message close and open again

I have a problem with alert messages. It is displayed normally, and I can close it when the user presses x (close), but when the user tries to display it again (for example, click on the button event) then it is not shown. (Moreover, if I print this alert message to console, it is equal to [].) My code is here:

 <div class="alert" style="display: none">
   <a class="close" data-dismiss="alert">×</a>
   <strong>Warning!</strong> Best check yo self, you're not looking too good.
 </div>

And event:

 $(".alert").show();

P.S! I need to show alert message only after some event happened (for example, button clicked). Or what I am doing wrong?

This question is related to javascript jquery twitter-bootstrap alert

The answer is


I just used a model variable to show/hide the dialog and removed the data-dismiss="alert"

Example:

<div data-ng-show="vm.result == 'error'" class="alert alert-danger alert-dismissable">
    <button type="button" class="close" data-ng-click="vm.result = null" aria-hidden="true">&times;</button>
    <strong>Error  !  </strong>{{vm.exception}}
</div>

works for me and stops the need to go out to jquery


The problem is caused by using the style="display:none", you should hide the alert with Javascript or at least when showing it, remove the style attribute.


I agree with the answer posted by Henrik Karlsson and edited by Martin Prikryl. I have one suggestion, based on accessibility. I would add .attr("aria-hidden", "true") to the end of it, so that it looks like:

$(this).closest("." + $(this).attr("data-hide")).attr("aria-hidden", "true");

I ran into this problem as well and the the problem with simply hacking the close-button is that I still need access to the standard bootstrap alert-close events.

My solution was to write a small, customisable, jquery plugin that injects a properly formed Bootstrap 3 alert (with or without close button as you need it) with a minimum of fuss and allows you to easily regenerate it after the box is closed.

See https://github.com/davesag/jquery-bs3Alert for usage, tests, and examples.


So if you want a solution that can cope with dynamic html pages, as you already include it you should use jQuery's live to set the handler on all elements that are now and in future in the dom or get removed.

I use

_x000D_
_x000D_
$(document).on("click", "[data-hide-closest]", function(e) {_x000D_
  e.preventDefault();_x000D_
  var $this = $(this);_x000D_
  $this.closest($this.attr("data-hide-closest")).hide();_x000D_
});
_x000D_
.alert-success {_x000D_
    background-color: #dff0d8;_x000D_
    border-color: #d6e9c6;_x000D_
    color: #3c763d;_x000D_
}_x000D_
.alert {_x000D_
    border: 1px solid transparent;_x000D_
    border-radius: 4px;_x000D_
    margin-bottom: 20px;_x000D_
    padding: 15px;_x000D_
}_x000D_
.close {_x000D_
    color: #000;_x000D_
    float: right;_x000D_
    font-size: 21px;_x000D_
    font-weight: bold;_x000D_
    line-height: 1;_x000D_
    opacity: 0.2;_x000D_
    text-shadow: 0 1px 0 #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="alert alert-success">_x000D_
  <a class="close" data-hide-closest=".alert">×</a>_x000D_
  <strong>Success!</strong> Your entries were saved._x000D_
</div>
_x000D_
_x000D_
_x000D_


There's a very simple way to do this using JQuery

If you delete data-dismiss="alert" from the alert div, you can just hide the alert using the x button, by adding a click events and interacting with the display css attribute of the alert.

$(".close").click(function(){
   $(this).parent().css("display", "none");
});

Then, whenever you need it again, you can toggle the display attribute again.

Full Example:

<div class="alert alert-danger" role="alert" id="my_alert" style="display: none;">
   Uh Oh... Something went wrong
  <button type="button" class="close" aria-label="Close">
     <span aria-hidden="true">&times;</span>
  </button>
</div>

<script>
   $(".close").click(function(){
      $(this).parent().css("display", "none");
   });

   //Use whatever event you like
   $("#show_alert").click(function(){
      $("#my_alert).css("display", "inherit");
   });
<script>

Based on the other answers and changing data-dismiss to data-hide, this example handles opening the alert from a link and allows the alert to be opened and closed repeatedly

$('a.show_alert').click(function() {
    var $theAlert = $('.my_alert'); /* class on the alert */
    $theAlert.css('display','block');
   // set up the close event when the alert opens
   $theAlert.find('a[data-hide]').click(function() {
     $(this).parent().hide(); /* hide the alert */
   });
});

This worked for me best:

$('.alert').on('close.bs.alert', function (e) {
    e.preventDefault();
    $(this).hide();
});

Can this not be done simply by adding a additional "container" div and adding the removed alert div back into it each time. Seems to work for me?

HTML

<div id="alert_container"></div>

JS

 $("#alert_container").html('<div id="alert"></div>');          
 $("#alert").addClass("alert alert-info  alert-dismissible");
 $("#alert").html('<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>Info!</strong>message');

All of the above solutions use external libraries, either angular or jQuery, and an old version of Bootstrap. So, here is Charles Wyke-Smith's solution in pure JavaScript, applied to Bootstrap 4. Yes, Bootstrap requires jQuery for its own modal and alerts code, but not everyone writes their own code with jQuery any more.

Here is the html of the alert:

<div id="myAlert" style="display: none;" 
    class="alert alert-success alert-dismissible fade show">
    <button type="button" class="close" data-hide="alert">&times;</button>
    <strong>Success!</strong> You did it!
</div>

Note that initially the alert is hidden (style="display: none;"), and instead of the standard data-dismiss="alert", we have here used data-hide="alert".

Here is the JavaScript to show the alert and override the close button:

var myAlert = document.getElementById('myAlert');
// Show the alert box
myAlert.style.display = 'block';
// Override Bootstrap's standard close action
myAlert.querySelector('button[data-hide]').addEventListener('click', function() {
    myAlert.style.display = 'none';
});

If you wish to hide or show the alert programmatically elsewhere in the code, just do myAlert.style.display = 'none'; or myAlert.style.display = 'block';.


If you're using an MVVM library such as knockout.js (which I highly recommend) you can do it more cleanly:

<div class="alert alert-info alert-dismissible" data-bind="visible:showAlert">
   <button type="button" class="close" data-bind="click:function(){showAlert(false);}>
        <span aria-hidden="true">&times;</span>
        <span class="sr-only">Close</span>
   </button>
   Warning! Better check yourself, you're not looking too good.
</div>

http://jsfiddle.net/bce9gsav/5/


I've tried all the methods and the best way for me is to use the built-in bootstrap classes .fade and .in

Example:

<div class="alert alert-danger fade <?php echo ($show) ? 'in' : '' ?>" role="alert">...</div>

Note: In jQuery, addClass('in') to show the alert, removeClass('in') to hide it.

Fun fact: This works for all elements. Not just alerts.


Here is a solution based on the answer by Henrik Karlsson but with proper event triggering (based on Bootstrap sources):

$(function(){
    $('[data-hide]').on('click', function ___alert_hide(e) {
        var $this = $(this)
        var selector = $this.attr('data-target')
        if (!selector) {
            selector = $this.attr('href')
            selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }

        var $parent = $(selector === '#' ? [] : selector)

        if (!$parent.length) {
            $parent = $this.closest('.alert')
        }

        $parent.trigger(e = $.Event('close.bs.alert'))

        if (e.isDefaultPrevented()) return

        $parent.hide()

        $parent.trigger($.Event('closed.bs.alert'))
    })
});

The answer mostly for me, as a note.


I think a good approach to this problem would be to take advantage of Bootstrap's close.bs.alert event type to hide the alert instead of removing it. The reason why Bootstrap exposes this event type is so that you can overwrite the default behavior of removing the alert from the DOM.

$('.alert').on('close.bs.alert', function (e) {
    e.preventDefault();
    $(this).addClass('hidden');
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to alert

Swift alert view with OK and Cancel: which button tapped? Bootstrap Alert Auto Close How to reload a page after the OK click on the Alert Page How to display an alert box from C# in ASP.NET? HTML - Alert Box when loading page How to show an alert box in PHP? Twitter Bootstrap alert message close and open again How to handle login pop up window using Selenium WebDriver? How to check if an alert exists using WebDriver? chrome undo the action of "prevent this page from creating additional dialogs"