I have a Rails 6 app that uses jQuery and Bootstrap - including js elements from Bootstrap.
this code should show the modal, but only works in some places:
$("#modalOverlay").modal("show");
-
- run from console: works
-
- code returned from remote render (ujs): works
-
- code in included player.js file: error
player.js:126 Uncaught TypeError: $(...).modal is not a function
at Object../app/javascript/custom/player.js.hs.showModal (player.js:126)
at <anonymous>:1:4
I’m particularly frustrated because this seems like a simple thing that should just work, but it has become some kind of dark magic that I don’t understand.
Here is my setup (which I have cobbled together from internet comments and tutorials)
bootstrap & jQuery were both installed via yarn
#config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack');
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
noUiSlider: 'nouislider',
Popper: ['popper.js','default'],
})
)
module.exports = environment
#app/javascript/packs/application.js
require("@rails/ujs").start()
require("@rails/activestorage").start()
require("channels")
//copied from https://github.com/jasl/cybros_core/blob/master/app/javascript/packs/application.js
//via https://gorails.com/forum/how-to-use-bootstrap-with-webpack-rails-discussion
import JQuery from 'jquery';
window.$ = window.JQuery = JQuery;
import 'bootstrap'
require("nouislider")
require("custom/player.js")
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
// Styles
// These are imported separately for faster Webpack recompilation
// https://rubyyagi.com/solve-slow-webpack-compilation/
import "stylesheets/nouislider.scss"
and then the code which fails is
#app/javascript/custom/player.js
...
hs.showModal = function() {
$("#modalOverlay").modal("show");
}
..
note that this is included via application.js
calling hs.showModal() from the console (or running it any other way) gives the error
Uncaught TypeError: $(...).modal is not a function
at Object../app/javascript/custom/player.js.hs.showModal (player.js:126)
at <anonymous>:1:4
can anyone explain what is going on and how I should fix it?
many thanks.