Switching between different alert classes in Bootstrap 4 can cause the alert type to malfunction

I am in the process of developing an alert system for a web application using Bootstrap 4. Below is the code I have implemented:

function bsalert(str1, str2) {

    $(".alert").addClass('show');

    $(".alert").addClass('alert-'+str1);

    $('.alert').html(str2);

    setTimeout( function() {
        $(".alert").removeClass('show');
        $(".alert").removeClass('alert-'+str1);
    }, 2000 );

}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">


<div class="alert alert-dismissible fade text-center" role="alert" id="alert"></div>

<button type="button" class="btn btn-outline-primary" onclick="bsalert('danger', 'ALERT!');">one</button>

<button type="button" class="btn btn-outline-primary" onclick="bsalert('success', 'nice');">two</button>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec9c839c9c899ec2869facddc2dddac2dc">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

The challenge I'm encountering is that if the alert is triggered too rapidly before the timer removes the class, it disrupts the ability to change the alert types. How can this issue be resolved? Is there a more efficient built-in function in Bootstrap that can handle this?

Edit: Although this example showcases a simplified version with only danger and success alert types, in reality, there are more variations available.

Answer №1

i trust this will be of assistance to you

var timer;
function bsalert(str1, str2) {

      clearTimeout(timer)
      $(".alert").removeClass('show');
      $(".alert").removeClass('alert-danger');
      $(".alert").removeClass('alert-success');

    $(".alert").addClass('show');

    $(".alert").addClass('alert-'+str1);

    $('.alert').html(str2);
    
    timer=setTimeout( function() {
        $(".alert").removeClass('show');
        $(".alert").removeClass('alert-'+str1);
    }, 2000 );

}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">


<div class="alert alert-dismissible fade text-center" role="alert" id="alert"></div>

<button type="button" class="btn btn-outline-primary" onclick="bsalert('danger', 'ALERT!');">one</button>

<button type="button" class="btn btn-outline-primary" onclick="bsalert('success', 'nice');">two</button>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

Answer №2

Utilizing the set timeout function allows for the alert to disappear within a 2-second interval. If multiple clicks on the notification occur during this time, the element will still be hidden after 2 seconds, resulting in a rapid disappearance effect. There are several solutions to address this issue: assigning a unique id to each notification element, restricting or delaying the function call, temporarily disabling the notification button for 2 seconds to ensure it is only triggered once every 2 seconds, and utilizing the clear timeout function in JavaScript.

var timeoutElem;

function bsalert(str1, str2) {
  var alertClassString = 'alert-' + str1;
  var existingClass = '';
  clearTimeout(timeoutElem);
  existingClass = (str1 === "danger") ? 'alert-success' : 'alert-danger';
  $(".alert").removeClass(existingClass);
  $(".alert").addClass(alertClassString);
  $(".alert").removeClass('show');
  $(".alert").addClass('show');
  $('.alert').html(str2);
  timeoutElem = setTimeout(function() {
    $(".alert").removeClass('show');
  }, 2000);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">


<div class="alert alert-dismissible fade text-center" role="alert" id="alert"></div>

<button type="button" class="btn btn-outline-primary" onclick="bsalert('danger', 'ALERT!');">one</button>

<button type="button" class="btn btn-outline-primary" onclick="bsalert('success', 'nice');">two</button>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" 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

Enhance the appearance of the activated header - Ionic 3 / Angular 5

On the current page, I want to emphasize the title by underlining it or changing its color - something that clearly indicates to the user which page they are on. Currently, I am utilizing lazy loading for navigating between pages, using modules for each pa ...

What is the best way to prevent a sticky element from scrolling along with the

I am looking to prevent a sticky div from taking up space on the website. It currently sticks to the desired position as expected. https://i.sstatic.net/wG4SK.png HTML <div v-if="isToastActive" class="toast"> <span clas ...

Retrieve the initial span within a <div> by using the data-id

Looking to access the initial span element inside a div? To retrieve the DOM element of the div, use the following code snippet: helper: function(event,ui){ var dataId = $(this).data('id'); console.log($('[data-id=" ...

Finding the date of a month prior based on a fixed initial date - here's how!

I have a specific requirement to display a subscription date range on a webpage in the following format: 31 May 2023 — 30 June 2023 When a user subscribes, the backend sends a fixed subscription start date that remains constant. For example, if a user ...

Using Hibernate to store Ajax responses in an ArrayList

I am currently working on a project that requires specific functionality: if the user selects a particular type from a dropdown menu, then the corresponding data should be displayed in the next dropdown menu. For example, there are 3 lists - pricelist, sla ...

Attempting to control an array of objects

In my current records: The parts with IDs 14.3, 14.2, and 14.1 belong to part ID = 30. The goal is to achieve the following: 1) By default, the first two IDs will be selected. If a user tries to select ID = 71, which belongs to part 30, they should not ...

Effortless Like/Unlike feature with a text button option enhanced with ajax functionality and

Struggling to create a simple Like/Unlike button in PHP without refreshing the page. Despite an abundance of tutorials on AJAX and jQuery, implementation remains elusive due to lack of experience. Uncertain where each part of the code goes within which fil ...

What is the best way to find the maximum and minimum values within a nested array in JavaScript?

I am looking to extract the highest and lowest values from specific data points within a nested array. For example, this nested array is structured as [latitude, longitude]. The specific nested array in question looks like this: [[40, 50], [50, 60], [60, ...

Best practices for managing jqGrid AJAX requests

Looking to create a more flexible solution in jqGrid by setting up a custom function for AJAX calls instead of hard-coding the URL in the definition. I've experimented with a few approaches, but haven't found one that perfectly mirrors the direc ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

Exploring the fnServerData function in DataTables

I have integrated Datatables into my project and I am really interested in the "fnServerData" callback option. After reviewing the documentation Here, I came across the example code below: $(document).ready( function() { $('#example').dataTabl ...

Refresh the homepage of a website using React Router by clicking on the site's logo from within the Home component

In most cases, when you click on a website's logo while on the homepage, it typically reloads the page. However, with React, clicking on the logo while already on the Home component does not trigger a reload. Is there a way to work around this issue? ...

What is the best way to activate an input field when a checkbox is selected in JQuery?

I'm encountering an issue with some code I've written. Here is the portion causing trouble: $('#Reserve, #BuyItNowPrice, #featureplate').attr('disabled','disabled'); $('.fake-fieldset .fake-input').css({&a ...

Issue with Hover behavior not being implemented on Android Webview

On my webpage, I have multiple CSS hover styles implemented using both the :hover pseudo selector and the cursor property. However, when loading this webpage in an embedded WebView on an Android device equipped with a mouse (such as Chromebooks), the CSS h ...

Using a JavaScript "for each" loop instead of having several "if

Could you please provide guidance on where to proceed? There are multiple input rows, with each row containing a field with the class row_changed If the value in the field is greater than 0, ajax will send the entire row to PHP. Each row is wrapped in a ...

The hierarchy of script loading in Angular applications

After years of working with MVC, I recently delved into Angular. Although I am well-versed in JavaScript and HTML, I'm still a beginner in the world of Angular. I spent hours troubleshooting my app only to realize that the problem was elusive. The a ...

The functionality of Bootstrap is currently malfunctioning within the ReactJS code

I am trying to implement Bootstrap for a table in ReactJS. I have the following code where I used class="container" in the <div> and class="table table-striped" in the <table>, however, the Bootstrap styles are not being applied. Can you help m ...

Is there a way to redirect the user to a different page without refreshing the page during navigation?

Utilizing javascript, ajax, and jquery to dynamically load content from PHP files without refreshing the page has been a successful venture. However, I am facing a challenge in creating a hyperlink within one of the loaded contents that redirects the user ...

d3 bar chart with overlapping bars - define x and y coordinates

Here is a glimpse of the data I am working with: var students = [ {'race': 'Black', 'count': 7, 'year': 2004, 'allnames': ['G Brown', 'F Clarkson', 'E Miller', 'R Black& ...

Executing callback functions after numerous asynchronous calls have been completed

Is there a method to delay the execution of a specific line of code until multiple API calls have all returned? Typically, I follow this pattern: APIService.call(parameter).then(function(response) { // Do something callBack(); }); This approach wo ...