Question

I'm using Rails 4. This snippet from my shared.js.coffee works fine without turbolinks:

jQuery ->
  $('input.autocomplete,textarea.autocomplete').each (index, item) =>
    sel = $(item)
    sel.autocomplete
      source: sel.data('autocomplete-source')
      minLength: 1

But when I use Turbolinks, it only works on a page refresh. It does not work after navigating through the site.

I've read Rails 4, Turbolinks, and Delegated Event Handling in jQuery, so I have some idea of what is going wrong, but I'm not yet sure how to fix the problem.

And, a related question: can anyone comment definitely if the jQuery UI autocomplete plugin -- or for that matter, plugins in general -- is/are designed to work with Turbolinks?

Was it helpful?

Solution

Use jQuery Turbolinks.

"if you have a large codebase with lots of $(el).bind(...) Turbolinks will surprise you. Most part of your JavaScripts will stop working in usual way. It's because the nodes on which you bind events no longer exist."

Usage:

# Gemfile:
gem 'jquery-turbolinks'

# JavaScript manifest file:
//= require jquery.turbolinks

Perhaps, at some point, the jQuery $.widget function will offer an option to bind differently, but until then, this works. No other changes to the Javascript are required.

OTHER TIPS

I recently had this problem with Rails 5 and the latest version of turbolinks(as of 8/24/17)

I had something similar. My issue was when navigating to another page withing my application and using autocomplete. it didnt work. after some research, I found that adding

$(document).addEventListener('turbolinks:load', function(){
 // your code here
}

to my

app/assets/javascripts/application.js

You can read some more about turbolinks here: turbolinks.

I hope this helps someone else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top