jqueryruby-on-railsbootstrap-4ruby-on-rails-5.1jquery-rails

jQuery conflict on Rails


My application.js:

//= require rails-ujs
//= require jquery
//= require activestorage
//= require turbolinks
//= require bootstrap-sprockets
//= require flatpickr.min
//= require_tree .

My Gemfile:

gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'bootstrap-sass'
gem 'jquery-rails'

If I I just leave my app like that, all my jQuery will work fine. But I also need

<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"</script>
</head>

on my application.html.erb since I am using Bootstrap 4.

So with this configuration, I am experiencing lot of issues with my jQuery, like

$(...).flatpickr is not a function

Is there a way to avoid those conflicts? I suppose that's because I'm including multiple jQueries on my app.

If I remove //= require jquery all the Bootstrap-related jQuery will work, but my custom scripts won't.
If I remove <script src="https://code.jquery.com/jquery-3.3.1.min.js"</script> my scripts will work but all Bootstrap-related won't (like the hamburger navbar or similars).


Solution

  • Here are the steps to add bootstrap 4 to your rails 5 application here are the links to rubygems and github pages.

    Step 1: Add bootstrap and jquery-rails to your Gemfile(Ensure that sprockets-rails is at least v2.3.2)

    gem 'bootstrap', '~> 4.2.1'
    gem 'jquery-rails'
    

    Step 2: Add Bootstrap dependencies and Bootstrap to your application.js

    //= require jquery3
    //= require popper
    //= require bootstrap
    

    You don't need to specify the cdn of jquery on your views that's the function of the line //= require jquery3. And remove your bootstrap-sass dependency which is for bootstrap 3

    Note: Important to notice that you need to require jquery3 with //= require jquery3