0

I am trying to figure out why my Bootstrap 5 Modal Event only seems to fire when I use pure JavaScript (addEventListener show.bs.modal for example), but when I try the same thing in jQuery the event doesn't fire.

    var myModal = document.getElementById('detailModal')
    myModal.addEventListener('show.bs.modal', function (event) {
        alert("I show correctly when the Modal opens!")
    })

    $('#detailModal').on('show.bs.modal', function (event) {

        alert('I do not show...');
    })

    // Also does not work...
    $('#detailModal').modal('show');

It may be because of my use of Webpack to include the Bootstrap/jQuery libraries (I am a total Webpack beginner). The Webpack configuration file is below...

const path = require('path')
const webpack = require('webpack');


module.exports = {
    entry: {
        site: './JsSrc/main.js',
        reporttemplate: './JsSrc/ReportTemplateDetails.js'
    },
    output: {
        filename: '[name]compiled.js',
        path: path.resolve(__dirname, 'wwwroot','js')
    },
    mode: 'development',
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(eot|woff(2)?|ttf|otf|svg)$/i,
                type: 'asset'
            }
        ]
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]
}

Because referencing with pure JavaScript works, I can continue with that, but I am concerned that it is not working with jQuery could be a sign that I am doing something else wrong (either configuration of Webpack or otherwise).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Louis Miles
  • 353
  • 1
  • 2
  • 8
  • Does this answer your question? [How to open a Bootstrap modal window using jQuery?](https://stackoverflow.com/questions/13183630/how-to-open-a-bootstrap-modal-window-using-jquery) – Emre Bener Dec 16 '22 at 12:46
  • Unfortunately I don't think so - as in my original example when I run the following $('#detailModal').modal('show') it doesn't show the modal.... – Louis Miles Dec 16 '22 at 12:59

1 Answers1

1

I found the answer in How do I load the Bootstrap 5 jQuery plugins in an ES6 project using Webpack?.

It turns out that Bootstrap 5 checks if jQuery exists in the window object (details on that are on Still want to use jQuery? It’s possible!), so in my Webpack entry JavaScript file, I added the following.

import $ from "expose-loader?exposes=$,jQuery!jquery";
window.jQuery = $;

And hey presto it now works! There may be better ways of doing this while using Webpack, but this does at least explain why it wasn't working initially and makes it work "good enough" for now...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Louis Miles
  • 353
  • 1
  • 2
  • 8