Implementing Bootstrap JavaScript functionality within a Rails 7 application

My current Rails 7 application utilizes esbuild as the JS bundler and has bootstrap imported. I am facing an issue where I am unable to access any Bootstrap Javascript functionality outside of the main application.js file. For example, I am attempting to programmatically display a Bootstrap modal on a specific page using the following code:

var myModal = new bootstrap.Modal(document.getElementById('helpModal'), {});
myModal.modal('show');

However, I am encountering an error as 'bootstrap' is not recognized:

Uncaught ReferenceError: bootstrap is not defined

Even though the page includes application.js:

<%= javascript_include_tag "application", defer: true %>

Do you have any suggestions on how to access 'bootstrap' in JS outside of the application.js file itself?

Thank you!

Answer №1

If you started your rails app with the command:

rails new APP_NAME --css=bootstrap ...

It sets up your app with ESBUILD and provides a app/javascripts/application.js file that looks like this:

// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
import * as bootstrap from "bootstrap"

Now, you will need to implement the modal functionality using the imported bootstrap.

Insert the following code after the bootstrap import line in your application.js file:

// Modals
var myModal = new bootstrap.Modal(document.getElementById('helpModal'), {});
myModal.modal('show');

// Or to have it triggered using a button
document.getElementById('helpModalButton').addEventListener('click', event => {
  myModal.show();
});

By doing this, you will activate the event handlers

For more detailed instructions, refer to the Bootstrap Docs page for Components such as Modals and Popovers.

https://getbootstrap.com/docs/5.1/components/modal/#passing-options

Answer №2

By declaring Bootstrap on the window object in application.js, I was able to get this working smoothly.

// app/javascript/application.js
import * as bootstrap from "bootstrap"
window.bootstrap = bootstrap;

// In the view
:javascript
  new window.bootstrap.Modal('#helpModal').show();

To easily close the modal when clicking on "Close" or "Submit," the following code proved effective:

<button type="button" class="btn btn-secondary" 'data-bs-dismiss'="modal">Close</button>

<%= form.submit "Submit", class: "btn btn-primary", 'data-bs-dismiss': "modal" %>

Simply adding the attribute "data-bs-dismiss" to the submit button will automatically close the modal upon submission.

Answer №3

If you encounter an error in an imported library and are unsure how to resolve it, one approach is to reference Bootstrap from a JS file within your app. In my case, I dealt with this issue by duplicating the

import * as bootstrap from "bootstrap"
command in my Javascript file...

//app/javascript/popovers.js

console.log('Loading popovers...')

import * as bootstrap from "bootstrap"

const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]')
const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl))

Subsequently, I imported that file from my main application.js:

//app/javascript/application.js

// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
import * as bootstrap from "bootstrap"
import "./popovers.js"

In my scenario, I was attempting to reference bootstrap in order to initialize Popovers.

Answer №4

After making a crucial decision, I deleted Gemfile.lock from my project and proceeded to update the gems using the command gem update --system. To ensure everything runs smoothly, don't forget to install the gems using bundler with the command bundle install. Best of luck with your project!

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

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...

Testing with Phantom/Casper in a browser-based environment

Currently, I am utilizing Casper for UI testing on websites. My main concern is regarding the compatibility testing in various browsers such as IE, Chrome, and Firefox using Casper. If this cannot be achieved with Casper, I am open to alternative methods ...

Is there a way to integrate jQuery and Javascript into a Firefox add-on?

Having trouble creating a new element on the page? After checking both the page and domain during onload, it seems that everything is in order. But how can you successfully create a new element in the correct window page? window.addEventListener("load", f ...

Struggling with a 400 Bad Request Error in Angular with WebAPI Integration

I've been working on creating a database to keep track of comics, and so far I can successfully add new comics and retrieve them using GET requests. However, I've hit a roadblock when trying to update existing comics using PUT requests. Every tim ...

Determine the amount of unused vertical space within a block of text

Having applied CSS to a span element: font-height = 120px; height = 120px; line-height = 120px; The text inside the span does not completely fill the height of 120px. Is there a method to determine the offset of the text from the top and bottom boundar ...

display in a modal-body and jdata

Within my MySQL database, there are several columns stored, including: headline, description, place, resume Currently, I am able to display the headline and description in a modalbox using the following code. However, I now wish to also showcase the pl ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Issue with Next JS router.push not functioning unless the page is refreshed

I'm currently running Next.js 14.2 in my project with the page directory structure. After building and starting the application using npm start, a landing page is displayed with a login button that utilizes the <Link> component. I have also disa ...

The art of effectively conveying arguments to the callback function

Here's a react App component that takes in a settingsobj object along with a callback function: export const settingsObj = { handlers: { onClick: (e, dispatch) => { console.log('Click event triggered from settingsObj', e); dispat ...

Compilation error in Angular 7 development process

Using Angular 7, npm 5.5.1 and node 8.9.0 In the terminal... npm run build:test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5435252503736d736d73">[email protected]</a> build:test C:\Projects\fff ng ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

Greetings! I am looking for information on how to activate CORS in a Ruby on Rails API application deployed on OpenShift for use with an Angular

My current setup involves a script utilizing Angular to display records fetched from a Rails API REST, which is hosted in OpenShift. In my public/.htaccess file, I have included the following directives: Header add Access-Control-Allow-Origin "*" Header a ...

PHP fails to retrieve data from a JavaScript Ajax function using the FormData object (specifically, when

I'm facing an issue where my file is not being detected when I send a FormData object using AJAX and PHP code. Both the `$_FILES` array and the `$_POST` array appear to be empty. However, the browser does send the file with the AJAX request. <inpu ...

Ways to show text in a password field

I'm looking to have the password field on a page. I'd like to show the text "Enter password" on the screen before the user starts entering their password, but once they focus on the field to enter their password, it should switch back to password ...

Get ready for 10 AM with the RxJS timer function

I am trying to figure out how to schedule a method in my code using rxjs/timer. Specifically, I want the method to run at precisely 10 AM after an initial delay of 1 minute. However, my current implementation is running every 2 minutes after a 1-minute d ...

Creating a javascript function to update content on click

Recently, I've been designing a webpage and encountered an issue. I want the text in a specific area to change whenever a user clicks on a link. Below is the code snippet related to the section I want to modify using a JavaScript function. <div id ...

What could be the reason for axios yielding [object Promise] rather than the actual data?

My issue involves a function that retrieves data from an API. However, when I integrate this function into an EJS template, it returns a promise instead of the desired data. Strangely, when I console.log the data, it displays the correct information. Assi ...

How can we enforce that the input consists of digits first, followed by a space, and then

Can regex (with javascript possibly) be used to mandate numbers, followed by a space, and then letters? I'm a bit lost on where to start with this... I understand that using an HTML5 pattern would work for this... [0-9]+[ ][a-zA-Z0-9]+ However, I ...