With Turbolinks enabled, the page keeps all existing JavaScript and loads the new page into the body. If the previous page has JavaScript running with document.ready, this also runs on the new page.
I have a navbar that has the same elements on every page. I would like the navbar to highlight the current page it's on. If I have a controller 'Home' and add to its coffeescript file (using jquery-turbolinks)
$(document).ready ->
$("#navbarCollapse .nav a:contains('Home')").parent().addClass('active');
This will highlight the "Home" icon on every page I visit. I only want it active when the 'Home' view is rendered.
One solution would be to place that bit of JavaScript in the view. Is there a more elegant solution, so my views don't contain any JavaScript?
I don't think you have to do all of this, you can simply do something like that:
<ul class="nav">
<li class="<%= 'active' if params[:controller] == 'controller1' %>"> <a href="/link">Link</a> </li>
<li class="<%= 'active' if params[:controller] == 'controller2' %>"> <a href="/link">Link</a> </li>
<li class="<%= 'active' if params[:controller] == 'controller3' %>"> <a href="/link">Link</a> </li>
</ul>
You can also do something much more better by checking this question's answers.