5

I have a rails app that's using coffeescript. When I refresh the page or go to it directly using the URL, the following code works. When I click a link through to this page and try it out, it doesn't work at all. Why could that be?

jQuery ->
  console.log "Ready."
  $('form').on 'click', '.add_fields', (event) ->
    console.log "Click."
    time = new Date().getTime()
    regexp = new RegExp($(this).data('id'), 'g')
    $(this).before($(this).data('fields').replace(regexp, time))
    event.preventDefault()

After a reload, I get Ready and Click when appropriate, and it works. After a click through from another page, I don't get anything. I also get this deprecation warning from chrome, which I'm not sure how to fix since it's coming from within JQuery itself:

event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
jquery.js?body=1:5375

The error only shows up when the code above isn't working. Is chrome blocking it? I'm using jquery-rails (3.0.4)

2
  • 1
    Are you using Turbolinks? If so, the handler on the form is getting blown away when the DOM gets refreshed. You need to wrap it in a page:restore page:load type handler. Commented Nov 27, 2013 at 20:39
  • Yes I am. I didn't realize I was at first. Thanks for that!! Commented Nov 28, 2013 at 15:41

2 Answers 2

6

So it turns out it was turbolinks that was causing the problem. Thanks davidburber for pointing that out. Here's what I did to fix it (from Rails 4: how to use $(document).ready() with turbo-links)

ready = ->
  $('form').on 'click', '.remove_fields', (event) ->
    $(this).prev('input[type=hidden]').val('1')
    $(this).closest('fieldset').hide()
    event.preventDefault()


$(document).ready(ready)
$(document).on('page:load', ready)
Sign up to request clarification or add additional context in comments.

1 Comment

also had to add $(document).on('turbolinks:load', ready); to get this to work
4

There's another, more simple solution here.

When you use turbolinks, which is default since Rails 4, also include [jquery.turbolinks gem][1]

The instructions are quite easy.

  1. In your Gemfile add: gem 'jquery-turbolinks'
  2. In your JavaScript manifest (default: app/assets/javascripts/application.js.coffee):
    Require jquery.turbolinks immediately after jquery.
    Require turbolinks after your scripts.

Example:

#= require jquery
#= require jquery.turbolinks
#= require jquery_ujs

# ... your other scripts here ...

#= require turbolinks


With the above you neither need any change in you code nor lines:

$(document).ready(ready)
$(document).on('page:load', ready)

1 Comment

jquery-turbolinks is now deprecated: github.com/kossnocorp/jquery.turbolinks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.