Jecob Boman Jecob Boman - 4 months ago 72
Javascript Question

Bootstrap alert auto closing not working

I wrote a simple JQuery script to auto close each alerts on my web page in different time periods.

This is my JQuery code:

$(function() {
var alert = $('div.alert[auto-close]');
alert.each(function() {
var time_period = $(this).attr('auto-close');
setTimeout(function() {
$(this).alert('close');
}, time_period);
});
});


Here are my two sample alerts:

<div class="alert alert-danger alert-dismissible" role="alert" auto-close="3000">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
alert one
</div>
<div class="alert alert-success alert-dismissible" role="alert" auto-close="5000">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
alert two
</div>


Each alert has a custom attribute with value, which is used as alert closing time period.

For some reason alert closing is not working.

Answer

$(this) was changed inside the setTimeout scope. Cache it in a variable. that in my example.

$(function() {
  var alert = $('div.alert[auto-close]');
  alert.each(function() {
    var that = $(this);
    var time_period = that.attr('auto-close');
    setTimeout(function() {
      that.alert('close');
    }, time_period);
  });
});

WORKING SNIPPET:

$(function() {
  var alert = $('div.alert[auto-close]');
  alert.each(function() {
    var that = $(this);
    var time_period = that.attr('auto-close');
    setTimeout(function() {
      that.alert('close');
    }, time_period);
  });
});
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="moo" class="alert alert-danger alert-dismissible" role="alert" auto-close="3000">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
  </button>
  alert one
</div>
<div class="alert alert-success alert-dismissible" role="alert" auto-close="5000">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span>
  </button>
  alert two
</div>