Rails - Conflicts between jQuery and javascript

I'm having a problem loading gems into my Rails 4 app.

I use jQuery. In my application.js, I have:

//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require html.sortable
//= require disqus_rails
//= require moment
//= require bootstrap-datetimepicker
//= require pickers
//= require main
//= require hammer.min
//= require jquery.animate-enhanced.min
//= require jquery.countTo
//= require jquery.easing.1.3
//= require jquery.fitvids
//= require jquery.magnific-popup.min
//= require jquery.parallax-1.1.3
//= require jquery.properload
//= require jquery.shuffle.modernizr.min
//= require jquery.sudoSlider.min
//= require jquery.superslides.min
//= require masonry.pkgd.min
//= require rotaterator
//= require smoothscrolljs
//= require waypoints.min
//= require wow.min
//= require gmaps/google
//= require chosen-jquery
//= require cocoon
//= require imagesloaded.pkgd.min
//= require isotope.pkgd.min
//= require jquery.counterup.min
//= require jquery.pjax
//= require custom.js
//= require slider
//= require dependent-fields
//= require bootstrap-slider

jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
    $(document).ready(function() {

//= require_tree .

In my gem file, I am trying to use rails dependent fields gem. That gem also requires underscore.js.

I think the reason this gem isn't working is because it uses javascript.

I'm having the same problem with the disqus rails gem (which is raising errors that are localhost/:94 Uncaught TypeError: $ is not a function

Does anyone know how to resolve conflicts between rails jQuery and javascript?



The problem is that you have set jQuery to work in noConflict mode through this line: $.noConflict();. jQuery will not define $ variable globally and will be available through jQuery variable only.

$.noConflict();   // <=====  HERE  ======
jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
    $(document).ready(function() {

The "plugins" that are raising this error are probably expecting $ variable to be set. They should not be doing that however.

You have 2 options:

  1. Remove $.noConflict(); line from your application.js file.
  2. Wrap the code that is raising this error in to a function where $ is set to jQuery variable.

Like this:

  // Here: $ === jQuery
  // Put js code that raises error here

Also, you are using 2 document ready events in your code. You can improve it to this:

jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.

Try to wrap your javascript code where you use $ variable with anonymous function:


// put your code here



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.