Search code examples
jqueryruby-on-railsturbolinks

Rails, Turbolinks and spinner


I am trying to replace a text link with a spinner on click. I have this:

$(document).on('page:fetch', function(e) {
  $('.spinner').replaceWith( "<img src='<%= asset_path('layout/spinner.gif') %>'>" );
});

But it is obvious that all links with the .spinner class gets the spinner. I want to replace only on the clicked link and only IF it has the spinner class.

Any suggestions?


Solution

  • You'll have some code which gets triggered on both 'page:load' and ready events so that they work for full page loads and Turbolinks page loads. The code below will add a 'data-click' attribute with value of true on the '.spinner' that was clicked.

    #inside both the ready and 'page:load' events
    $('.spinner').on('click', function(e) {
      $(this).attr('data-clicked', true);
    });
    

    The code below will look for the '.spinner' with a data-clicked attribute with value of true and apply the spinner image on it.

    $(document).on('page:fetch', function(e) {
      $('.spinner[data-clicked="true"]').replaceWith( "<img src='<%= asset_path('layout/spinner.gif') %>'>" );
    });
    

    Let me know if that helps.