Friday, November 15, 2013

Javascript Alert For Unsaved Changes with Turbolinks, Jquery, And Rails 4

jQuery change event can be used to detect form change. But because Turbolinks pages will change without full reload, we can't rely on DOMContentLoaded or jQuery.ready() to trigger change event. Here is how to write jQuery change event code with Turbolinks enabled. Tested with Rails 4.0.0.

# Coffeescript

ready = >
  # your jquery code
  # ...

# page:load is fired at the end of the loading process.
$(document).ready(ready)
$(document).on('page:load', ready)

change = ->
  $("form input, form textarea").change( ->
    $('a').click( ->
      confirm('Unsaved changes on the page. Are you sure?')
    )
  )

$(document).ready(change)

# the page has been parsed and changed to the new version and on DOMContentLoaded
$(document).on('page:change', change)


# Javascript

# ...
change = function() {
  $("form input, form textarea").change(function() {
    $('a').click(function() {
      confirm('Unsaved changes on the page. Are you sure?');
    });
  });
}; 
# ...


Gist: https://gist.github.com/kuntoaji/7472721

1 comment: