4

I have a Rails 5.1 app in which I am using the sortable.js library from https://www.kryogenix.org/code/browser/sorttable/ in order to do some simple client-side sorting of tables.

I am running into an issue where, when the page first loads, the table sorting does not work. (It just doesn't respond at all.) If you then manually reload the page (cmd-R or equivalent), then it does work.

After some searching, I believe that the problem is being caused by turbolinks. Posts like this one, and others suggest how to modify the JS code to solve it: Rails javascript only works after reload

To quote from the answer on that page you have to tell turbolinks to load by doing this:

document.addEventListener("turbolinks:load", function() {
  my_func();
})

I, however, am not a JS expert, and so am a bit loathe to monkey around in the sortable.js code too much. I'm looking for help as to the least invasive way to solve the problem.

Q A
  • 101
  • 6

1 Answers1

5

Posting a working solution, for the sake of future Google-ers.

I had to do two things to get this to work:

1: Comment out to lines at the top of the init function which prevent it from running more than once. So the top of my init function in sorttable.js looks like this:

    sorttable = {
      init: function() {
        // Had to comment these top to out to get things to work with turbolinks
        // quit if this function has already been called
        //if (arguments.callee.done) return;
        // flag this function so we don't do the same thing twice
        //arguments.callee.done = true
  1. Add this code somewhere else in the file. (I personally added it after the line that says "window.onload = sorttable.init;"

    document.addEventListener("turbolinks:load", function() {
      sorttable.init();
    })
    
Q A
  • 101
  • 6