Tips for prolonging the visibility of the Bootstrap 5 Toast alert

Within my HTML code, I have defined a toast element:

<div class="position-fixed top-0 start-50 translate-middle-x" style="z-index: 9999">
    <div id="errNeutralAlreadyExists" class="toast fade bg-solid-white"
         role="alert" aria-live="assertive" aria-atomic="true"
         data-bs-animation="true" data-bs-autohide="true" data-bs-delay="3000">
        <div class="toast-header">
            <strong class="me-auto js-toast-title">Toast Title</strong>
        </div>
        <div class="toast-body">
            Content of the toast message will go here
        </div>
    </div>
</div>

Although the toast works correctly, I am looking to make it disappear slowly rather than abruptly vanishing. I attempted to assign a class for this purpose, but it doesn't seem to have the desired effect:

.toast.hide {
  transition-duration: 1s;
 }

How can I achieve a slow, graceful disappearance for the toast message?

const toastTrigger = document.getElementById('liveToastBtn')
const toastLiveExample = document.getElementById('errNeutralAlreadyExists')

if (toastTrigger) {
  toastTrigger.addEventListener('click', () => {
    const toast = new bootstrap.Toast(toastLiveExample)

    toast.show()
  })
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9cbc6c6dddeddcbc7dbcdce8bd4dbcb97c0c8cf">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-jr2vpqO2s2g5zhTbs42g3h7to3Yk3gluFLjQ/KW2Fg6uyKiw2VV7rgVKd5vva" crossorigin="anonymous">

<button type="button" class="btn btn-primary" id="liveToastBtn">Display live toast</button>

<div class="position-fixed top-0 start-50 translate-middle-x" style="z-index: 9999">
  <div id="errNeutralAlreadyExists" class="toast fade bg-solid-white" role="alert" aria-live="assertive" aria-atomic="true" data-bs-animation="true" data-bs-autohide="true" data-bs-delay="3000">
    <div class="toast-header">
      <strong class="me-auto js-toast-title">Toast Title</strong>
    </div>
    <div class="toast-body">
      Content of the toast message will go here
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086a67677c6f6f6d6e69505164f3517e636a6e656b54655a61">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-18ZIxfFwWswrEKLCT6TONNyN9qGuxBmCuKd+rcKOfLjeSMUTF/tA1giqDkcN9" crossorigin="anonymous"></script>

Answer №1

I implemented some JavaScript code to check when the element is about to be shown or hidden, and then applied different CSS styles accordingly:

.fadeSlow {
      transition: opacity 1s ease-out !important;
}

The custom CSS class overrides the default behavior only when the element is fading out. Here's the JavaScript code I added:

toastLiveExample.addEventListener('hide.bs.toast', () => {
  $("#errNeutralAlreadyExists").addClass("fadeSlow");
})
toastLiveExample.addEventListener('show.bs.toast', () => {
  $("#errNeutralAlreadyExists").removeClass("fadeSlow");
})

If you want to adjust the speed of the fade-out effect, you can modify the CSS. I set it to 1s as an example, but the default is 0.15s.

I hope this explanation helps!

const toastTrigger = document.getElementById('liveToastBtn')
const toastLiveExample = document.getElementById('errNeutralAlreadyExists')

if (toastTrigger) {
  toastTrigger.addEventListener('click', () => {
    const toast = new bootstrap.Toast(toastLiveExample)
    toast.show();
  })
}
toastLiveExample.addEventListener('hide.bs.toast', () => {
  $("#errNeutralAlreadyExists").addClass("fadeSlow");
})
toastLiveExample.addEventListener('show.bs.toast', () => {
  $("#errNeutralAlreadyExists").removeClass("fadeSlow");
})
.fadeSlow {
      transition: opacity 1s ease-out !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43212c2c37303731223303766d716d70">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<button type="button" class="btn btn-primary" id="liveToastBtn">Show live toast</button>

<div class="position-fixed top-0 start-50 translate-middle-x" style="z-index: 9999">
  <div id="errNeutralAlreadyExists" class="toast fade bg-solid-white" role="alert" aria-live="assertive" aria-atomic="true" data-bs-animation="true" data-bs-autohide="true" data-bs-delay="3000">
    <div class="toast-header">
      <strong class="me-auto js-toast-title">Toast Title</strong>
    </div>
    <div class="toast-body">
      Toast message goes here
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="284a47475c5b5c5a4958681d061a061b">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7L+jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Revamp the UI Framework's CSS to accommodate the latest Web Components

I've implemented Grommet as the UI Framework for my React page. However, I encountered a situation where certain web components, like a web chat control, are not covered by Grommet's CSS. What is the simplest way to style these additional web com ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...

Tips for changing a div's visibility with radio buttons in jQuery

$(':radio').change(function(event) { var id = $(this).data('id'); $('#' + id).addClass('none').siblings().removeClass('none'); }); .none { display: none; } <script src="https://ajax.googleapis.com/ ...

Leveraging a shared directory within an npm project

In my Vue project, I have multiple clients with similar components stored in a "common" folder structure: clients -- client1 ---- ... -- client2 ---- ... -- client3 ---- ... -- common ---- imports.js ---- ... Currently, each project has its own package.j ...

Checking the Length using JQuery

My dilemma is with a text field (datepicker) - I want the button to change color when someone selects a date, but it's not working. Can you please assist me? HTML <input type="text" id="datepicker"> <button type="button" onclick="" class=" ...

Is it possible to showcase HTML content within a C# string in a straightforward manner?

I am attempting to achieve a specific format, similar to the following: string html = @"Hello <b> World ! </b>"; The intended result should look like this: Hello World ! The string html can be utilized on various elements such as label, t ...

Node Express JS: Efficiently handling multiple fetch responses before sending data to client

My goal is to call an API that only accepts one animal name at a time, but I receive the names of multiple animals in a query separated by commas. To achieve this, I plan to call the API once for each animal, push the JSON data into an array, and then resp ...

BeautifulSoup: A guide on retrieving information following a designated HTML element

I have the following HTML code and I am trying to determine how to instruct BeautifulSoup to extract the <td> data after the element <td>Color Digest</td> <tr> <td> Color Digest </td> <td> 2,36,156,38,25,0, ... ( ...

Choose a particular element within an element class using a variable as the selector in jQuery

Is there a way to dynamically add a class to a specific element in an array based on a variable in a for loop, rather than random selection? I need to target elements with the variable provided and possibly apply the class to more than one element if neces ...

When using jquery.hide() and show(), the content within the div disappears momentarily before reappearing

Hello! I am experiencing an issue where the content of my div disappears after using a jQuery hide() and show() function. It seems to be gone. <li class="gg3"><a class="link" href="#" data-rel="content3">Link1</a></li> <div clas ...

Sidebar collapse using Bootstrap

I have been working on creating a collapsible sidebar that pushes the content on the right, but I'm facing issues with responsiveness. When I display the sidebar, the content is getting compressed instead of pushed. I tried adding flex-shrink-0 to the ...

Including files from different directories using PHP

I'm currently involved in a project for school. The index is functioning properly, however, when I click on 'Lab 1 Q1' located at labs/1/1.html, it does direct me to the page but my <?php include('/main-nav.php') ?> isn' ...

I encountered a problem in Javascript where I was unable to get the video.getCurrentTime() function to display the current time of

While everything else in my code is running smoothly with setInterval, there seems to be an issue with video.getCurrentTime() not displaying in the div id = "test" when the video is playing. I've been trying to figure out why this is happening. Here&a ...

Pass function A as a prop, then trigger a different function when the child function calls A

Apologies for the uninformative title; I struggled to come up with a suitable one regarding my issue. I have a question concerning React code. My Child component receives the onValueChanged function as a prop. This function was initially passed down to th ...

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

Optimize your website by caching static pages and content using Node.js

When it comes to caching static content using nodejs, there seem to be two main methods that can be utilized: The first method involves using nodejs and utilizing the following code: app.use(express.static(path.join(__dirname, 'public'), { max ...

Can a function be called when using ng-options with AngularJS select?

Here is some HTML code <select ng-model="selectedMarker" ng-options="shape.text for shape in Selects('shapes')"> </select> And below is the JavaScript code angular.module('todo', ['ionic']) . ...

Applying Border Radius to JavaFX Components for a Unique Background Effect

When I apply the CSS properties -fx-border-radius and -fx-border-width to a basic GridPane, the background in the corner does not get "cut off". The following is the CSS code being used: .payload { -fx-hgap: 20px; -fx-padding: 40px; -fx-back ...

When we find ourselves within a fat arrow function

I'm struggling with this code. I have a ternary operator within a fat arrow function, but for some reason it's not working. There are no errors in browserify or the console, but the headers are not being printed. If I remove the {} and ternary o ...

What's the best way to position a grid item so that it moves along with its fellow siblings

I am currently utilizing CSS Grids and I have a specific requirement. I need to offset an element so that it moves horizontally across the grid columns while maintaining its width. Additionally, I want the offset value to be added to the element's exi ...