Home > Software engineering >  Bootstrap 5.2 : Collapsing issues with Webpack and Javascript
Bootstrap 5.2 : Collapsing issues with Webpack and Javascript

Time:10-23

I am working on a project using HTML, SASS and JS with Webpack 5.74.0.

I want to use Bootstrap 5 to make collapsable, a feature I just did. Because I couldn't make it work, I tried to just copy/paste the example from the documentation to see what was wrong.

Here's the example :

<p>
  <a  data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
    Link with href
  </a>
  <button  type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
    Button with data-bs-target
  </button>
</p>
<div  id="collapseExample">
  <div >
    Some placeholder content for the collapse component. This panel is hidden by default but revealed when the user activates the relevant trigger.
  </div>
</div>

I am using the template feature of Webpack's html-loader (doc) to insert the HTML file in the page with JS :

webpack.config :

module: {
    rules: [
       ...
       {
        test: /\.html$/i,
        loader: 'html-loader',
       }
      ]
     }

The JavaScript code drawing the page :

import collapseExample from '../templates/collapseExample.html'

...

body.insertAdjacentHTML('beforeend',collapseExample)
//collapseExample being a string from the source code

When building, the page shows the two buttons from the example, and div#collapseExample is hidden. This bit of code is the exact same from the example of the documentation, so I don't think html-loader is at fault here.

However when I click either of the buttons, nothing happens. No error in the console, and div#collapseExample is not showing up at all. I had exactly the same problem when trying with my own code (being the feature is well hidden, but nothing happens when I click the button).

I built both using the local server (webpack serve --open --config {my Webpack config file}), and when Webpack puts the build files in dist. The issue remains the same. I am using up to date Firefox.

What's wrong with what I am trying to do ? Thanks for helping.

CodePudding user response:

Can you try manually initializing the collapsible? maybe it's added after bootstrap adds its listeners.

const bsCollapse = new bootstrap.Collapse('#myCollapse', {
  toggle: false
})

Lets try also, on the click event of the buttons (for debugging purposes)

var bsCollapse = new bootstrap.Collapse('#collapseExample', {
  toggle: false
})
bsCollapse.toggle()
  • Related