Display a custom toast from a list using Bootstrap 5

I've been utilizing the toast feature from Bootstrap, and it works perfectly when displaying a single toast. However, I encountered an issue when trying to display a specific toast, like an error toast, from a list of predefined toasts. It ended up showing all the other toasts as well. My goal is to display only one type of toast at a time, whether it's success, error, warning, etc. I experimented with the following code snippets but they didn't behave as expected.

$('.toast-error').show(); // displays all defined toasts instead of just the selected one
$('.toast-error').toast('show'); // also displays all defined toasts

Below is the HTML structure where I have included all the predefined toasts:

<div aria-live="polite" aria-atomic="true" style="position: relative;z-index: 999999">
  <div style="position: absolute; top: 0; right: 0;" class="p-1" id="toast-content">
    
    <div class="toast bg-success toast-success text-white mt-2" role="alert" aria-live="assertive" aria-atomic="true" data-bs-animation="true">
      <div class="toast-body">
        Welcome To Project.
        <button type="button" class="pull-right btn-close btn-close-white ms-auto me-2" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>

    <div class="toast toast-error bg-danger text-white mt-2" role="alert" aria-live="assertive" aria-atomic="true" data-bs-animation="true" style="display: none;">
      <div class="toast-body">
        Error Occured. Please Refresh Window.
        <button type="button" class="pull-right btn-close btn-close-white ms-auto me-2" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>

  </div>
</div>

<button class="w-100 btn btn-lg submit" type="button" onclick="validator()">Proceed</button>
<script>
 function validator(){
    $('.toast-error').show();
 }
</script>

Can anyone spot where my mistake might be?

Answer №1

Give this a shot, it could be beneficial for you.

<script type="text/javascript">
  function formValidator(){
 
   var userEmail    = $('#userEmail').val();
   var userPassword = $('#userPassword').val();

    if(userEmail.trim()==''){
     $('#toast-error').show();
     $('#toast-error').toggleClass('display');
     $('#userEmail').focus();
     return false;
  }
  if(userPassword.trim()==''){
     $('#toast-error').show();
     $('#toast-error').toggleClass('display');
     $('#userPassword').focus();
     return false;
  }
 }
 </script>

Answer №2

Solution-Inducing Comment:

Your issue stems from employing class selectors without further specification, causing all elements with that class to be affected. To rectify this, consider refining your JavaScript logic using various methods such as IDs, custom attributes, block selections with find(), or utilizing "this", among others.

The resolution came by utilizing IDs instead of relying on class as selectors.

Please review the relevant comments in the question for further context.

Answer №3

Although this post is now three years old and references BS4, it may still be helpful to someone who comes across it:

If you have a Toast List (explained in detail here), you can initialize individual Toasts and use them separately.

let toast = new bootstrap.Toast(document.getElementById('toastID'))
toast.show();

The Bootstrap Docs mention a getOrCreateInstance function, but it may not work in this specific case.

While this information may be coming quite late, hopefully it will provide some assistance to someone in need.

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

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Utilizing Print Styles in an Angular 7 Application: A Step-by-Step Guide

I'm trying to print an html form within my Angular7 App with minimal margins. I've attempted different solutions such as adjusting the margins manually in Chrome's print preview box and adding @media print styles & @page styles in both the c ...

The Google Pie chart is displaying outside of the designated div area when placed inside a dropdown menu

Encountering an issue with my pie chart rendering outside of its parent div when placed within a dropdown menu. The chart successfully loads after the page is loaded, but only displays correctly if I hover over the dropdown and allow it to load. If I do ...

A guide on changing the style of a Layout component in React

Currently, I am utilizing Next.js alongside Material-UI as the framework of choice. Within my project, there is a Layout component that encapsulates the content with Material-UI's <Container>. I desire to customize the style of the Layout compon ...

Tired of the premium content on Medium.com. How can I conceal premium posts that are aimed at a specific class within a parent element?

I have noticed that all Premium posts contain an element with the class ="svgIcon-use" <svg class="svgIcon-use" width="15" height="15" viewBox="0 0 15 15" style=""><path d="M7.438 2.324c.034-.099.090 123 0l1.2 3.53a.29.29 0 0 0 .26.19h3.884c.11 0 ...

Allow only specific inner divs to dictate the width of the outer div

I'm working with the following HTML structure: <div id="container"> <div id="block1"> <img src="someimage/path" /> </div> <div id="block2"> Some Text </div> <div id="block3"&g ...

Customizing a ControlsFX PopOver in a JavaFX application

I am looking to personalize the appearance of a JavaFX PopOver control. I have a button that triggers the display of the PopOver. Below is a functional example: package custompopover; import javafx.application.Application; import javafx.event.ActionEvent ...

Tips for breaking out of the foundation row and aligning with the right edge of the viewport

I have a CodePen example showcasing the Zurb Foundation grid. I am looking for a way to make a div extend to the right edge of the viewport while keeping the left edge in line with the grid as the viewport is resized. <div class="row"> <div cla ...

Making a CSS table fit perfectly inside a container

After reading numerous recommendations on the subject, none of them seem to be effective in my particular situation. The issue lies with a table that is nested within a container ('div' element) as shown below: <div class="container"> ...

The Angular Material Table experienced a collapse when trying to render over 20 columns simultaneously

Currently, I am experiencing an issue in Angular Version 5 where the Angular Material Table collapses when rendering more than 20 columns. Here is a snapshot of what my table looks like: https://i.stack.imgur.com/MXfvQ.png https://i.stack.imgur.com/XHWgq ...

Struggling to align the footer of your webpage and ensure it adjusts proportionally with the window size?

After trying several codes that have worked before, I ran into a problem when attempting to place two div side by side for the footer. No matter what code I tried, I couldn't get it centered and responsive to the user window ratio. Even after consulti ...

What are some strategies for keeping the focus state on the parent item in a dropdown menu?

When I interact with the dropdown menu in my navigation bar, the color changes for the child items. How can I make sure that the parent item maintains the same colored background even after clicking elsewhere on the page? To better understand the issue, i ...

Ensuring Proper Alignment of Headers in CSS

I'm struggling to align my header correctly. Despite getting close in Internet Explorer, it looks terrible in Firefox with the code below. I've scoured forums for solutions but the more I try to fix it, the worse it looks. All I want is for heade ...

Emphasizing sections using a specific class for paragraph highlighting

Is it possible to dynamically change the style of paragraphs based on certain classes? Let's say we have a text with a list of p elements and we want to modify the styles of paragraphs that come after specific classes, such as 'alert' or &ap ...

Unable to match the height of the inner card image in bootstrap with the height of the outer card image

I'm facing an issue with two bootstrap cards, one nested inside the other, both containing images. Check out the StackBlitz here The inner image doesn't flex to the same height as the outer one, resulting in a small space between the two cards ...

Is it possible for images underneath to receive focus when hovering over them?

I'm struggling with a layout of thumbnails on my page. We'll refer to them as A, B, C, etc. They are currently displayed like this: A, B, C, D, E, F, G, H, I, J, K, L, M, N... and so on. When you hover over one thumbnail, it enlarges by 2.5 t ...

Is it normal that my website isn't scrollable on an iPhone?

I have a hunch that the issue is related to the CSS, or perhaps it could be due to including the parallax JavaScript library. You can view the site at Below is the SASS code snippet: @import "compass/css3"; /* Sticky footer styles ---------------------- ...

What could be causing my divs to overlap?

I recently started coding and I'm facing an issue with my <header> and <section> divs overlapping each other. I was under the impression that being block elements, <section> should be displayed below <header>. Any suggestions o ...

Is there a way to eliminate the transform style from a draggable element?

I am looking to enhance the CDK drag and drop example by adding a preview of the dragged element with specific left and top positions, without utilizing the transform style. HTML <div class="example-boundary"> <div class="example- ...

Accessing the parent element within a hover declaration without explicitly naming it

I am facing a challenge with three nested divs, where I want to change the color of the children when the parent is hovered. However, I prefer not to assign a specific class name to the parent element. The issue arises because the children have their own ...