Using Webpacker with Ruby on Rails 6 presents a limitation when attempting to call Bootstrap4 $('.carousel').carousel

While working with Ruby on Rails 6 and webpacker, I attempted to incorporate a carousel slide similar to this example (Bootstrap 4 Card Slider). However, upon clicking the button to show the next (or previous) slide, an error message "Uncaught TypeError: $(...).carousel is not a function" appeared in the console. Even when I directly entered the script '$('.carousel').carousel' in the console, the same error persisted. I came across information suggesting that loading JQuery multiple times can lead to such errors, but I'm unsure if I've made that mistake. Any suggestions or advice on my codes below would be greatly appreciated.

app/views/home_page/test.html.erb

<%= javascript_pack_tag "carousel" %>

<section class="container p-t-3">
    <div class="row">
        <div class="col-lg-12">
            <h1>Bootstrap 4 Card Slider</h1>
        </div>
    </div>
</section>
<insert your modified code here>

app/javascript/packs/carousel.js

(function($) {
    "use strict";

    // manual carousel controls
    $('.next').click(function(){ $('.carousel').carousel('next');return false; });
    $('.prev').click(function(){ $('.carousel').carousel('prev');return false; });

})(jQuery);

config/webpack/environment.js

app/javascript/packs/application.js

app/javascript/src/application.scss

package.json

Answer №1

Here is a snippet from my environment.js file:

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)

module.exports = environment

This code enables jquery to work with webpacker.

In your application.scss file, make sure to include the following line:

@import '~bootstrap';

Your test.html.rb file may need some adjustments. Here is a simplified version without cards and styling:

<section class="container">
  <h1>Bootstrap 4 Card Slider</h1>
</section>
<section class="container">

  <a class="btn btn-lg" href="#carouselExample" role="button" data-slide="prev">
    <span> &laquo; </span>
  </a>
  <a class="btn btn-lg" href="#carouselExample" role="button" data-slide="next">
    <span> &raquo; </span>
  </a>

  <div id="carouselExample" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
      <div class="carousel-item active">
        <img class="d-block w-100" src="http://i.imgur.com/EW5FgJM.png" alt="First slide">
      </div>
      <div class="carousel-item">
        <img class="d-block w-100" src="http://i.imgur.com/Hw7sWGU.png" alt="Second slide">
      </div>
      <div class="carousel-item">
        <img class="d-block w-100" src="http://i.imgur.com/g27lAMl.png" alt="Third slide">
      </div>
    </div>
  </div>
</section>

To enable this functionality without using carousel.js, utilize data attributes as shown above. Once everything is working smoothly, you can then reintroduce cards and additional styling.

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

How can I prevent duplicate IDs when submitting a form through AJAX within a while loop?

While submitting a form using Ajax within a while loop, I encountered an issue where the same form ID is being used multiple times due to the loop. As a result, the form only submits once. I believe that I need to generate a unique ID for each iteration of ...

Combining Rails with React.js: Concealing data from sight

Within my Rails + React application, I am faced with an issue on the index page where all data is being mapped over. However, upon inspecting the element, I noticed that React is exposing the complete contents of the Rails object in the root react element. ...

BackboneJs error: Cannot call undefined as a function

Having encountered a persistent issue with no resolved solutions on Stack Overflow, I am revisiting this problem. For reference: Uncaught TypeError: undefined is not a function rails3/backbone/js Currently working on my first app using backBoneJs and fol ...

What is the best way to have a form open upwards when hovered over or clicked on?

Attempting to create a button in the bottom right corner that will reveal a form when clicked or hovered over. The form should slide open slowly and close after clicking on login, but currently the button is moving down as the form opens. The button also ...

JavaScript or Query: Transforming an Object from an Associative Array

Can someone help me out with converting an associative array into an object in JavaScript? I tried searching on Stackoverflow but couldn't find a working example. Here is the example structure: var combinedproducts = [["Testing-1","test-1"],["Testin ...

Discover the secrets of monitoring a class method with node-jasmine

My current setup includes a User module structured as follows: module.exports = User = (function() { function User(params) { this.id = params.id; this.first_name = params.first_name || ''; this.last_name = par ...

Navigating URL to switch data access

Is there a way to toggle the visibility of a div when I add #ID at the end of the URL? For instance, if I access a URL like domain.com/xxxxxx#01, then the specified div should be displayed. $(document).ready(function() { $(".toogle_button_<?php echo ...

Error message "$injector:unpr" occurs in the run method of AngularJS after minification process

I've encountered an issue with angular-xeditable on my Angular app. While it functions properly in the development environment, I'm facing an error in production when all JS files are minified: Uncaught Error: [$injector:strictdi] http://errors. ...

What is the method for utilizing keycodes inside an array to determine which keys are recognized as input in a 'keyup' event listener?

I'm currently working on creating a game similar to Wordle, but I've hit a roadblock when it comes to filtering out only the alphabet keys as valid keyboard inputs for the game. Within my Keyboard container, I have rows of keys and a JavaScript ...

Include the ordinal indicator when a data entry is present in node.js

Currently, I am appending a timestamp as a prefix to the filename if it already exists in order to make it unique. However, I would like to enhance this by implementing an ordinal suffix. This means that if a file with a certain filename, like "helloworld ...

Achieving full route matching in Express.js, including subroutes

I'm in the process of creating a node js application that should display a 404 page for all routes except for the /video route. app.get('/video/*', Video.show) app.get('*', (req,res) => res.render('not_found')) Every ...

Encountering the "TypeError: document.getElementById(...) is null" error message while utilizing react.js in conjunction with chart.js

I am encountering an issue while using react and chart.js together to create a bar chart. The problem lies in the fact that chart.js requires the use of canvas tags, and we need to locate this tag and insert the bar chart within it using the traditional do ...

Encountering a 400 Bad Request error when attempting to post data, but still managing to successfully save

CODE OPERATION: STORING USER DATA IN DATABASE AS A NEW APP USER REGISTRATION. ISSUE: DATA IS SAVED, BUT RECEIVING "400 BAD REQUEST" AND ERROR MESSAGE IN CONSOLE ERROR: "Cannot save() the same document multiple times in parallel" SCRIPT (GENERATING JWT T ...

Ensure the central alignment of the focused item within the horizontal scroll

I have successfully implemented a horizontal scroll container using <HTML/> and CSS: body { background-color: #212121; } .scroll_container { height: 100px; width: 400px; display: flex; align-items: center; overflow-y: hidden; width: 1 ...

Ways to transmit data multiple times within a single request

I'm currently developing an app using Nodejs and express, where orders can be placed for specific products. In this application, when an order is received, it is saved in the database and a PDF receipt is generated immediately. However, since generati ...

The nodejs events function is being triggered repeatedly

I have been developing a CMS on nodejs which can be found at this link. I have incorporated some event hooks, such as: mpObj.emit('MP:FOOTER', '<center>MPTEST Plugin loaded successfully.</center>'); Whenever I handle this ...

Activate the saturation toggle when a key is pressed in JavaScript

I am trying to modify a script that currently toggles the value of a variable when a key is pressed and then lifted. Instead of changing the variable value, I would like to adjust the saturation of the screen based on key presses and releases. How can I ac ...

The drop-down box options on the web page are not visible to me, but I am able to see them in the element

Having a peculiar issue with two dropdowns on my webpage. The first dropdown works perfectly fine, but when I click on the second dropdown, the options don't show up on the webpage, even though they are visible in the element window. Both dropdowns ha ...

What is the best way to utilize lodash in order to inspect every element within a collection, excluding those that do not fulfill my specified condition

let allChecked = _.every(this.collection, this.checked); I'm working on tweaking an existing code snippet that currently evaluates to true if every item in the collection has the checked property set to true. My goal is to adjust it so that it only c ...

Is the RadioButton change jQuery function malfunctioning following modifications to the DOM?

After updating the HTML of the radio button (with the same name) through AJAX based on certain logic (such as rate or duration changes), I noticed that the change(function(e) method worked perfectly before the DOM was updated. However, once the DOM chang ...