Toasts in Bootstrap 5
Bootstrap Toasts
Bootstrap Toasts are used to display simple notifications or messages to users.
They are positioned at the bottom right corner of the screen by default, but can be positioned at other locations as well.
As an example:
Editor
Loading...
In this example:
- We created a toast element inside a container with the class
position-fixed
bottom-0
end-0
p-3
to position it at the bottom right corner of the screen. - The toast element contains a
toast-header
and atoast-body
. - The
toast-header
contains a title and a close button, while thetoast-body
contains the message that we want to display. - We then used JavaScript to create a
new bootstrap.Toast
object and passed in the toast element as the first argument. - We also called the
show()
method on the object to display the toast message.
Open a Toast
To open a Bootstrap Toast, you can create a new bootstrap.Toast()
object in JavaScript and call its show()
method.
As an example:
Editor
Loading...
In this example:,
- We have created the toast message using bootstrap toast.
- Toast class to initialize and show the toast.
- The
button
tag with theid
attribute set tomyButton
creates a clickable button that can be selected in JavaScript using thequerySelector()
method. - The
div
tag with the classtoast
creates a container for a Bootstrap toast notification, which is a small pop-up message that appears on the screen. - The
script
tag contains JavaScript code that selects the button and the toast container usingquerySelector()
, and then attaches an event listener to the button usingaddEventListener()
. - When the button is clicked, the code creates a new
Toast
object from the Bootstrap JavaScript library and passes it the toast container as an argument. - The
show()
method is then called on theToast
object to display the notification.