1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.