Search code examples
ruby-on-railscoffeescript

Why occur Uncaught ReferenceError: $ is not defined coffeescript in rails 5.2?


I using coffee script in Rails 5.2: Refer at: http://guides.rubyonrails.org/working_with_javascript_in_rails.html

My code: welcome/index.html.erb:

<a href="#" onclick="paintIt(this, '#990000')">Paint it red</a>
<a href="#" onclick="paintIt(this, '#009900', '#FFFFFF')">Paint it green</a>
<a href="#" onclick="paintIt(this, '#000099', '#FFFFFF')">Paint it blue</a>

welcome.coffee:

@paintIt = (element, backgroundColor, textColor) ->
  element.style.backgroundColor = backgroundColor
  if textColor?
    element.style.color = textColor

$ ->
  $("a[data-background-color]").click (e) ->
    e.preventDefault()

    backgroundColor = $(this).data("background-color")
    textColor = $(this).data("text-color")
    paintIt(this, backgroundColor, textColor)

But it not working and occur error: Uncaught ReferenceError: $ is not defined enter image description here

My Gemfile had add:

gem 'jquery-rails'

application.js:

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

Why occur Uncaught ReferenceError: $ is not defined coffeescript in rails 5.2?


Solution

  • My problem was resoled by change order lib:jquery go to above turbolinks

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

    to

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