Cyril Duchon-Doris Cyril Duchon-Doris - 9 months ago 27
Javascript Question

Turbolinks and Bootstrap Tab activation

I am basically facing the same problem as described here, under the additional context of Rails' Turbolinks.

I am using this piece of code

$(document).on('ready page:change', function() {
/* Show tab from anchor */
var hash = window.location.hash;
hash && $('ul.nav a[href="' + hash + '"]').tab('show');

/* Update URL anchor after selecting tab */
$('.nav-tabs a').click(function (e) {
var scrollmem = $('body').scrollTop();
window.location.hash = this.hash;

Which does work for manual page reload (F5) and for cache restore, but not after reloading the page from a Turbolinks click*.

*When clicking a turbolinks link, if there is some cache of the page, then that cache is first restored and the good tab is shown, but then thre is still a request to the server to get the last contents, and once that request arrives and is parsed, the tab "switches back" to the original one

My bootstrap code looks like this

<ul class="nav nav-tabs" role="tablist">
<li class="nav-item">
<a class="nav-link active" data-toggle="tab" href="#student" role="tab"></a>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#mentor" role="tab"><%= </a>
<li class="nav-item">
<a class="nav-link" data-toggle="tab" href="#company" role="tab"></a>

<!-- Tab panes -->
<div class="tab-content">
<br />
<div class="tab-pane fade in active" id="student" role="tabpanel">
<div class="tab-pane fade" id="mentor" role="tabpanel">
<div class="tab-pane fade" id="company" role="tabpanel">


Rails 5 comes with Turbolinks 5. The solution was just to change the name of the event listener

$(document).on('ready turbolinks:load', function() {