Bootstrap 4 - Bootstrap Toasts

Bootstrap Toasts

Toast giống như alert box chỉ hiển thị trong vài giây khi có điều gì đó xảy ra (có thể khi người dùng click vào button, submit form, vv).

Cách để tạo một Toast

Để tạo toast, sử dung class .toast, sau đó add .toast-header và .toast-body bên trong nó:

<div class="toast">
  <div class="toast-header">
    Toast Header
  </div>
  <div class="toast-body">
    Some text inside the toast body
  </div>
</div>

Xem ví dụ

Chú ý: Toasts phải được khởi tạo với jQuery: : chọn phần tử được chỉ định và gọi phương thức toast().

Đoạn code sau sẽ show all "toasts" trong trang:

<script>
$(document).ready(function(){
  $("#myBtn").click(function(){
    $('.toast').toast('show');
  });
});
</script>

Ví dụ:

<div class="container">
  <h3>Toast Example</h3>
  <p>A toast is like an alert box that is only shown for a couple of seconds when something happens (i.e. when a user clicks on a button, submits a form, etc.).</p>
  <p>In this example, we use a button to show the toast message.</p>
 
  <button type="button" class="btn btn-primary" id="myBtn">Show Toast</button>

  <div class="toast">
    <div class="toast-header">
      Toast Header
    </div>
    <div class="toast-body">
      Some text inside the toast body
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
  $("#myBtn").click(function(){
    $('.toast').toast('show');
  });
});
</script>

Xem ví dụ


Show/Hide một Toast

Toasts theo mặc định là hidden. Sử dụng thuộc tính data-autohide="false" để hiển thị chúng theo mặc định. Để đóng toast, sử dụng <button> và add data-dismiss="toast":

<div class="container">
  <h3>Toast Example</h3>
  <p>In this example, we use data-autohide="false" to show the toast by default. You can close it by clicking on the close (x) icon inside the toast header.</p>

  <div class="toast" data-autohide="false">
    <div class="toast-header">
      <strong class="mr-auto text-primary">Toast Header</strong>
      <small class="text-muted">5 mins ago</small>
      <button type="button" class="ml-2 mb-1 close" data-dismiss="toast">&times;</button>
    </div>
    <div class="toast-body">
      Some text inside the toast body
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
  $('.toast').toast('show');
});
</script>

Xem ví dụ