Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to disable Turbolinks for specific jQuery Ajax calls to prevent the page from refreshing and scrolling?

I have a Rails 5 application and would very much like to use Turbolinks.

Within the application there are several PATCH ajax calls that simply update the server with new data, but do not need to worry about updating the state of the page.

Whenever these ajax requests return, Turbolinks refreshes the page and the browser scrolls to the top of the screen. This is not desirable behavior; it is much preferred that things just stay put where they are.

Disabling Turbolinks eliminates the problem.

Example (super basic) ajax call that causes the problem:

$.ajax({
  method: "PATCH",
  url: url,
  data: obj
});

Is anyone else experiencing this or have any ideas on how to prevent the page scroll from occurring?

like image 653
mindtonic Avatar asked Apr 01 '16 16:04

mindtonic


People also ask

How do I disable Turbolinks?

If you want to disable Turbolinks for certain links, add a data-turbolinks="false" attribute to the tag: <a href="..." data-turbolinks="false">No turbolinks here</a>.

What does Turbolinks do with your browser's history?

Turbolinks saves a copy of the current page to its cache just before rendering a new page. Note that Turbolinks copies the page using cloneNode(true) , which means any attached event listeners and associated data are discarded.

How does Turbolinks work?

Turbolinks Overview It works by intercepting all link clicks that would navigate to a page within the app, and instead makes the request via AJAX, replacing the body with the received content. The primary speedup comes from not having to download or parse the CSS & JS files again.

Whats Turbolinks?

If you're a Rails developer, chances are that you know Turbolinks. Turbolinks is a flexible and lightweight JavaScript library aimed to make your navigation through webpages faster. Turbolinks improves webpage performance by substituting the common full-page loads for partial loads in multi-page applications.


2 Answers

Had the same problem and found a solution via another StackOverflow question.

The idea is to make a JS request to Rails (using the dataType and format options):

$.ajax({
    method: "PATCH",
    url: url,
    dataType: 'script',
    format: 'js',
    data: obj
});

In your rails controller, simply respond to this JS call with:

respond_to do |format|
    format.js
end

No page reload!

like image 156
Ced Avatar answered Oct 04 '22 15:10

Ced


I found the answer here: Turbolinks documentation on Github.

Step 1: replace the usual document.ready with a custom turbolinks:load.

step 2: make sure to specify that the type is json

document.addEventListener('turbolinks:load', function() {
// your ajax code: 
    $.ajax({
        method: 'PATCH',
        url: url,
        dataType: 'json'
    })
}
like image 32
Katinka Hesselink Avatar answered Oct 04 '22 13:10

Katinka Hesselink