All threads / Turbolinks and jQuery compatibility on Rails 5

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Turbolinks and jQuery compatibility on Rails 5

Lauro asked in Javascript

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
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 34,885+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.