Rails 7 is missing the Toast element from Bootstrap 5

Having some trouble with implementing Bootstrap 5 Toast in Rails 7 for flash messages. Here is the code I am currently using:

# application.html.erb
<head>
...
<%= javascript_importmap_tags %>
<script>
    const toastElList = document.querySelectorAll('.toast')
    const toastList = [...toastElList].map(toastEl => new bootstrap.Toast(toastEl))
    console.log(toastElList);
</script>
</head>

<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>
...

# application.js
//= require jquery3
//= require popper
//= require bootstrap-sprockets

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"

The Bootstrap JavaScript seems to be functioning properly as the dropdown menu works fine.

I manually added the .toast element for testing purposes. However, when I check console.log(toastElList), it appears to be empty without any elements found.

Any ideas on how to make this Toast display and disappear automatically?

Answer №1

I made a rookie mistake by not waiting for the window to load before trying to access elements. That's why they couldn't be found initially. Here's the updated code snippet:

<script>
  window.onload = (event) => {
    const toastElList = document.querySelectorAll('.toast')
    const toastList = [...toastElList].map(toastEl => new bootstrap.Toast(toastEl))
    console.log(toastElList);
  };
</script>

By using window.onload, the elements are now successfully located.

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 toggling journal entries in an HTML journal? The Jquery function might not be working properly

I have been tasked with creating a civil war journal for my 8th grade Social Studies class and I decided to present it as an HTML file featuring the title and date of each journal entry. The goal is to allow users to click on each entry to open it while au ...

What is the best way to access the form button inside a div element?

Here is the code snippet for my form: <form accept-charset="utf-8" action="https:example.com" method="get" name="test"> <div class="classy"><input type="button" class="buttonE ...

Developing a Simple Analytics Dashboard

As I plan to develop a fundamental Analytics page to delve deeper into Javascript, AJAX and alternative data storage methods like redis, I find myself pondering the optimal way to deliver user data. Should it be dynamically calculated at real-time for gr ...

Set a dynamic Active Class on various divisions by utilizing their respective indexes

I have two divs with the same class. When I click on an anchor tag within one of the elements, I want to add a class to the corresponding position in the second div as well. Mirror: JSFiddle Here is the jQuery code snippet: $(document).on('click ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Tips for implementing both an onChange and onSubmit event for a MUI TextField

I'm currently working with React and MUI and have created a form like the following: const handleUserInput = (event) => { set_user_input(event) } const handleSubmitForm = () => { if (user_input == 'help'){ ...

Is it possible to manipulate the response from a MySQL server using Node.js?

For example: The following response represents the original data { "todo_id": 2, "todo_item": "brush your teeth", "scheduled_time": "2020-03-22T07:14:29.000Z", "user_id": 1, "is_done": { "type": "Buffer" ...

Reduce code length for generating DOM fragment with jQuery

I'm currently working on generating a tree of elements that will be used as an input for JsTestDriver unit tests. I've got some code to create this tree which involves using Document Object Model methods in JavaScript. I'm wondering if there ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

What is the appropriate utilization of the await keyword within concise if-else statements in JavaScript?

Along with transitioning away from jQuery, my main focus is to make my code more efficient. In large scale enterprise applications, the excessive use of jQuery and JavaScript can become problematic. I have decided to switch back to vanilla JavaScript for ...

The layout of the keyboard in Cordova has been altered

Just starting out with my first Cordova app and I'm working on a simple login form. The issue I'm facing is that whenever I click on an input element, the keyboard pops up and completely messes up my layout, which should be straightforward. Has ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Guide to utilizing jquery within node.js

Can anyone assist me with using jQuery in Node.js? I have the following code: const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM('<!DOCTYPE html>'); const $ = require('jquery')(window); var con ...

Issue with VueJs and ChartJs not displaying custom options when making an API call

Having trouble populating my chart with data from the API. Despite setting extraOptions for my chart, it defaults to default options when rendered. Here is the component code: import { Bar, mixins } from 'vue-chartjs'; export default { name: ...

Obtain the name of the client's computer within a web-based application

I am working on a Java web application that requires the computer name of clients connecting to it. Initially, I attempted to retrieve this information using JavaScript and store it in a hidden form field. However, I discovered that JavaScript does not hav ...

What is the best way to transfer XML data format from a web browser to a server using jQuery?

Is there a method in jQuery to transmit data to the server from a browser in XML format? Thank you, Sana. ...

Leveraging the power of ReactJS for efficiency in executing multiple API calls concurrently

I'm encountering an issue with the following code snippet: let tmpContributors = [...this.state.contributors]; for (let i = 0; i < 10; i++) {//10 most active contributors due to performance and github limits contributorPropertiesPromises.pus ...

There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it ...

Tips for retrieving modified data from a smart table in Angular 4

Currently, I am working on an angular project where I am utilizing smart table. Here is a snippet of my .html file: <ng2-smart-table [settings]="settings" [source]="source" (editConfirm)="onSaveConfirm($event)" (deleteConfirm)="onDeleteConfirm($event ...

Having trouble formatting an AJAX POST request properly

Despite my best efforts, I continue to encounter the dreaded 500 (Internal Server Errors) every time I try to execute a POST request to https://rates.tradelanes.us/bankaccount/record/create. I suspect it has something to do with the format of my data. Howe ...