Search code examples
ruby-on-rails-4turbolinks

Is there a way to have (hack) turbolinks to only refresh a specific selector?


I would like to use turbolinks in a rails 4 application but not have it replace the entire <body> tag. Instead I would like to specify a tag/selector for turbolinks to refresh.

Something like...

<body>
  <div class="turbolinks-refreshes-this">
    Some content that is replaced whenever a link is clicked.
  </div>
  <div class="turblinks-does-not-refresh-this">
    Some content that remains even if a link is clicked.
  </div>
</body>

My guess is you would need to fork turbolinks to add this functionality but thought I'd throw it out there to see if anyone else has tried to do this.


Solution

  • Have you looked at pjax? It's very similar to Turbolinks (and gets a mention in the Turbolinks README) but lets you specify a target container. Here's a Railscast that shows how to use it in a Rails app.

    Here's a (slightly modified) excerpt from the pjax README:

    <h1>My Site</h1>
    <div class="container" id="pjax-container">
      Go to <a href="/page/2">next page</a>.
    </div>
    

    We want pjax to grab the url /page/2 then replace #pjax-container with whatever it gets back. No styles or scripts will be reloaded and even the h1 can stay the same - we just want to change the #pjax-container element.

    We do this by telling pjax to listen on a tags and use #pjax-container as the target container:

    $(document).pjax('a', '#pjax-container')
    

    Now when someone in a pjax-compatible browser clicks "next page" the content of #pjax-container will be replaced with the body of /page/2.