Skip to main content

Turbolinks and jQuery compatibility on Rails 5

Javascript • Asked by 6696

I have a hidden field that's activated when clicked on the link using jQuery. When clicking on the link, the field appears just for a second and then disappears.

  $('.use-different-card').on "click", ->
    $(".card-on-file").hide()
    $(".card-fields").removeClass("hidden")

When I remove turbolinks, jQuery seems to work just fine.

I've tryied adding compatibility.coffee but I had no luck.

And using:

$(document).on "turbolinks:load", ->

This is my source tree.

//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require turbolinks
//= require turbolinks-compatibility
//= require_tree .

Anything suggestion on what to try next?


Have you try $(".card-fields").show() instead of $(".card-fields").removeClass("hidden") ?!

In case it fail, don't use class hidden, add in-line style there: style="display:none;". And now $(".card-fields").show() will work.


Hey Anh,

What do you mean in-line style? Where shoudl I add that?

I also tried adding:

  $(document).on 'turbolinks:before-visit', ->
  $('.use-different-card').on "click", ->
    $(".card-on-file").hide()
    $(".card-fields").removeClass("hidden")

Ah I mean inline CSS. For example:
<div class="card-fields hidden"> will be <div class="card-fields" style="display:none">


I see what you mean Anh. Thanks for the help!

I noticed that if the element with .use-different-card is an <a>, I needed to cancel the click event:

$('.use-different-card').on "click", (event) ->
  event.preventDefault()
  $(".card-on-file").hide()
  $(".card-fields").removeClass("hidden")

or

$('.use-different-card').on "click", ->
  $(".card-on-file").hide()
  $(".card-fields").removeClass("hidden")
  false

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.