How to bind an jQuery onclick event with Coffeescript, in Rails? How to bind an jQuery onclick event with Coffeescript, in Rails? ruby-on-rails ruby-on-rails

How to bind an jQuery onclick event with Coffeescript, in Rails?


I found the crux of the problem - My Coffeescript was fine, it was because of a gem called Turbolinks that the code was not triggering. It keeps the current page instance alive and replaces only the body and the title in the head, which means you can't rely on DOMContentLoaded or jQuery.ready() to trigger your code. This is why the script would seem to work when the page was hard refreshed (refresh clicked).

For those who use Turbolinks

  • If you want to opt out specific links

Add data-no-turbolink to the parent container of the link(s) like so...

<a href="/">Home (via Turbolinks)</a><div id="some-div" data-no-turbolink>  <a href="/">Home (without Turbolinks)</a></div>
  • If you have a lot of existing JavaScript that binds elements on jQuery.ready()

Using the event hook page:change, you can replace the jQuery.ready() with $(document).on 'page:change', -> or, even better $(document).on 'ready page:change', ->; better, because it means that even if turbolinks is not running (because of being on an old browser version maybe), the call will still trigger due to ready being there.

It is best to use page:change instead of page:load. The former event hook fires when the page is loaded from the server or from the client-side cache, whereas the latter event hook only fires when a new body element has been loaded into the DOM (source).

...or...

You can use the jquery-turbolinks gem.

Gemfile:

gem 'jquery-turbolinks'

bundle install and then add it to your JavaScript manifest file, in this order:

//= require jquery//= require jquery.turbolinks//= require jquery_ujs//// ... your other scripts here ...////= require turbolinks


I'd argue that you should be using event delegation anyway.

Try something like this and see if you get better results:

$ ->  $('body').on 'click', '.tabs_image', ->    # do stuff


load the dom with $(document).on 'ready page:load', -> instead of jQuery -> you can read more on the Rails Documentation