0

For my navigation bar, I have it so that when I click on one of the items, my css class "current-menu-item" is activated. This works to a certain extent. My Jquery code is as follows:

$(document).ready(function(){
  $("li.menu").click(function(){
    $("li.menu").removeClass("current-menu-item");
    $(this).addClass("current-menu-item");
  });
});

This is the rails link_to:

<li class="menu">
  <%= link_to "home", root_url %>
</li>

The only problem with this is that this code executes BEFORE the redirect. So I can only quickly see the class activate for a brief second before the new page loads and it is removed.

What is the easiest way to solve this dilemma?

Vasseurth
  • 6,354
  • 12
  • 53
  • 81
  • 1
    That is what we call default behaviour... – Adil Shaikh Jun 21 '13 at 20:55
  • 4
    Use your server code to put the class on the correct `li`, based on what was clicked. This is really the only way to do it, because technically they could remember/save the URL of the link, visit it later, and they won't see the correct thing (if you tried to use some client technology like cookies or `localStorage`). At the same time, you could let the JavaScript determine what page they are currently on (by investigating the `window.location.href`, or `window.location.pathname`) but I think that's messy and less maintainable – Ian Jun 21 '13 at 20:55

1 Answers1

0

If you are going to do this with JavaScript, and not on the server-side, you can compare window.location.pathname to the href attribute of your menu links.

Something like this:

$.each("li.menu", function(i, menuItem) {
  if (menuItem.attr("href") === window.location.pathname) {
    menuItem.addClass("current-menu-item");
  }
});

Keep in mind that this won't work unless your path name exactly matches the href attribute, so it's prone to error.

zxqx
  • 5,115
  • 2
  • 20
  • 28