Menu

Bootstrap 5 Toasts


Previous


Next

Toasts

The toast component is like an alert box that is only shown for a couple of seconds when something happens (i.e. when the user clicks on a button, submits a form, etc.).

How To Create a Toast

To create a toast, use the .toast class, and add a .toast-header and a .toast-body inside of it.

Note: Toasts are hidden by default. Use the .show class if you want to display it. To close it, use a <button> element and add data-bs-dismiss="toast":

Example

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Bootstrap Example</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css” rel=”stylesheet”>
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js”></script>
</head>
<body>

<div>
<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 the .show class to always show the toast by default. You can close it by clicking on the close (x) icon inside the toast header.</p>

<div>
<div>
<strong>Toast Header</strong>
<button type=”button” data-bs-dismiss=”toast”></button>
</div>
<div>
<p>Some text inside the toast body</p>
</div>
</div>
</div>

</body>
</html>

Open a Toast

To show a toast with a click of a button, you must initialize it with JavaScript: select the specified element and call the toast() method.

The following code will show all “toasts” in the document when you click on a button:

Example

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Bootstrap Example</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link href=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css” rel=”stylesheet”>
<script src=”https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js”></script>
</head>
<body>

<div>
<h3>Toast Example</h3>
<p>In this example, we use a button to show the toast message.</p>

<button type=”button” id=”toastbtn”>Show Toast</button>

<div>
<div>
<strong>Toast Header</strong>
<button type=”button” data-bs-dismiss=”toast”></button>
</div>
<div>
<p>Some text inside the toast body</p>
</div>
</div>
</div>

<script>
document.getElementById(“toastbtn”).onclick = function() {
var toastElList = [].slice.call(document.querySelectorAll(‘.toast’))
var toastList = toastElList.map(function(toastEl) {
return new bootstrap.Toast(toastEl)
})
toastList.forEach(toast => toast.show())
}
</script>

</body>
</html>


Previous


Next

Scroll to Top