Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript JQuery on click only working when page is refreshed

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)

like image 525
mscriven Avatar asked Nov 27 '13 20:11

mscriven


1 Answers

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)
like image 76
mscriven Avatar answered Sep 29 '22 13:09

mscriven