Unable to switch. Is there an issue with the initialization of Bootstrap 5 JavaScript?

I seem to be encountering an issue with my implementation of Bootstrap 5.0.0-beta2. While I can expand my navbars and accordions successfully, collapsing them does not work as expected.

It appears that the problem lies in the initialization of the JavaScript.

Interestingly, when I navigate from a page without these elements to a page containing them (thanks to hotwire/Turbo which prevents full page reloads), both expansion and collapse functionalities work. However, I do see some errors in the console related to toggling:

Uncaught TypeError: No method named "toggle"
    at Function.collapseInterface (bootstrap.bundle.js:1942)
    at bootstrap.bundle.js:2001
    at Array.forEach (<anonymous>)
    at HTMLButtonElement.<anonymous> (bootstrap.bundle.js:1985)
    at HTMLDocument.handler (bootstrap.bundle.js:414)

Any suggestions on what could be done differently to resolve this?

For context, I am using webpack to bundle assets for my Ruby on Rails application (leveraging the webpacker gem). Below is my webpacker configuration:

// app/javascript/packs/application.js

import Rails from "@rails/ujs"
import { Turbo } from "@hotwired/turbo-rails"
import "bootstrap"
import "../stylesheets/application"
window.Turbo = Turbo
window.bootstrap = require('bootstrap/dist/js/bootstrap.bundle.js')
Rails.start()
/* app/javascript/stylesheets/application.scss */

@import "~bootstrap/scss/bootstrap";
// config/webpack/environment.js

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend(
  'Provide',
  new webpack.ProvidePlugin({
    Rails: '@rails/ujs',
    Popper: ['popper.js', 'default']
  })
)
module.exports = environment

In addition, I have included some images showcasing the transitions when toggling after refreshing the page.

Here is the initial state:

https://i.sstatic.net/LYN9L.jpg

Upon toggling the navbar, it transitions as expected:

https://i.sstatic.net/YbU64.jpg

After expanding, it remains in the expanded state:

https://i.sstatic.net/ybW2D.jpg

However, pressing the navbar-toggler icon does not result in collapsing the navbar. Instead, it goes through the expanding animation (similar to the second image) and ends up expanded (like the third image).

Answer №1

Recently tested out Bootstrap 5.0.0-beta2, Rails 6.1 based on your setup code.

The issue appears to be related to how you are loading the bootstrap object, particularly this line:

// Encounter conflict here
window.bootstrap = require('bootstrap/dist/js/bootstrap.bundle.js')

You may consider using either const require or import as suggested in the documentation:

const bootstrap = require('bootstrap') or import bootstrap from 'bootstrap' will load all of Bootstrap’s plugins onto a bootstrap object.

const bootstrap = require('bootstrap') // or
import bootstrap from 'bootstrap'

Alternatively, you can globally load the bootstrap object:

// config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

environment.plugins.prepend(
  'Provide',
  new webpack.ProvidePlugin({
    Rails: '@rails/ujs',
    Popper: ['popper.js', 'default'],
    bootstrap: ['bootstrap']
  })
)

module.exports = environment

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

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

Tips on utilizing browser.getCurrentUrl() within a Protractor examination

I’ve been wrestling with these lines of Protractor code today: element(by.linkText("People")).click(); browser.waitForAngular(); var url = browser.getCurrentUrl(); ... It seems that getCurrentUrl always throws an error when placed after a waitF ...

My jQuery Ajax seems to have a glitch, can someone help me figure out

Looking for some help with this HTML code: <section id="login"> <form> <input type="text" name="username" size="10" placeholder="username" /> <input type="password" name="password" size="10" placeholder="password" ...

Is there a way for app.use to identify and match requests that begin with the same path?

Given that app.use() responds to any path that starts with /, why does the request localhost:3000/foo match the second method instead of the first? app.use("/",express.static('public'), function(req,res,next) { console.log(& ...

The state in useState is failing to update correctly following selections made within the dropdown menus

I am currently facing an issue with my dropdown disabling function, which is not enabling the dropdown properly. I suspect that this is due to asynchronous problems stemming from the use of useState. const [homeSelect, setHomeSelect] = useState('Home& ...

Run a targeted command on AWS Beanstalk

I have a unique node.js application that specifically functions with sqlite. I am interested in conducting a 'proof of concept' on AWS ElasticBeanstalk without the need to adjust the node.js app to be compatible with a supported database Prior ...

When navigating through a view in backbone.js, ensure to include an argument in the routing process

Looking to include an argument while routing within a Backbone.js application Below is the script: var AppRouter = Backbone.Router.extend({ routes: { 'toolSettings/(:action)' : 'toolSettings' } }); var initialize = function ...

Maximizing the power of Webpack alongside Google Maps API

I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API. Here is the code snippet: var map; function initMap() { map = new google.maps.Map(d ...

Encountering problem with JSON in the bodyParser function

I've encountered an issue while sending data from my React component using the Fetch API and receiving it as JSON on my Express server. When I try to parse the data using the jsonParser method from bodyParser, I only get back an empty object. Strangel ...

Unique background image is assigned to each div sharing the same class

Seeking a way to assign unique random backgrounds to each div with the .item class. Initially attempted using PHP and CSS, for example: <?php $bg = array('bg1.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg ...

What is the best way to utilize Node.js to serve a single page HTML file on port 80?

This is how my project structure is organized: project assets/images/ css/application.css js/application.js font node_modules index.html server.js package.json I am aiming to run 'node server.js" in the project directory and have it serve on port ...

Filter out all elements that come before the comma in the sorted array's output

Looking for a solution to modify my code so the output is just "Bothell" without the comma and count part. let As = document.getElementsByTagName('a'); let towns = new Map(); for(let a of As) { let town = a.textContent.split(',') ...

Real-time chat system using PHP for one-on-one inquiries with server-sent events (not a group chat)

I'm currently working on developing a live chat inquiry form for a website using HTML server-sent events. I'm utilizing this tutorial as a foundation Here is my plan based on the tutorial: On the client side, users are prompted to enter a use ...

jQuery was denied permission to implement inline styling due to non-compliance with the specified Content Security Policy directive

Currently, I am exploring the GitHub project play-silhouette-slick-seed, which serves as an illustration of the Silhouette authentication library for Play Framework in Scala. My goal is to incorporate it into my own project. However, while attempting to ru ...

Display images with sequential animation and a delay, combining fade-in and slide-up effects

I am attempting to create a cycling image display with specific effects: There should be a one-second delay before the first image is shown. The first image will appear with a fade-in and slide-up effect. Image #1 will remain visible for 5 seconds before ...

Compiling with Gulp Browserify may have longer processing times after each save or change

I have been working on improving the speed of my Gulp workflow by using Browserify. The approach I am taking is heavily influenced by this informative blog post: Initially, everything seems to be functioning well with changes reflecting quickly (around 50 ...

Disappear notification with jQuery after a set amount of time

I stumbled upon this amazing script for displaying warning messages from this source: Within the script, it is configured to hide the warning message following a click event. $('.message').click(function(){ $(th ...

Utilizing Angular JS to ensure services are universally accessible across controllers and views

Imagine we have a service like this: myApp.factory('FooService', function () { ... Now, from a controller, the code would look something like this: myApp.controller('FooCtrl', ['$scope', 'FooService', function ($s ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

Ensure to update the npm package version before making any Git commit

My project is built with Ember using NPM and I utilize Git for version control. I am looking for a way to update or bump the package.json version before or during a Git commit. Is there a method to accomplish this? Should I be implementing Git hooks? ...