Search code examples
javascriptcssmeteoriron-router

How Do I Properly Set Active Navigation Tab When Pressing the Back Button in Meteor Application?


I have a multipage meteor application with a navigation template included in each page.

I use iron-router to switch between pages.

I indicate which page the user is on by setting the appropriate navigation link's class to 'active.

Example: navigation.html

<li class="{{navClassName 'page1'}}">
  <a href="/page1">Page 1 </a>
</li>
<li class="{{navClassName 'page2'}}">
  <a href="/page1">Page 2 </a>
</li>

and in navigation.js:

Template.registerHelper('navClassName', function (page) {
  if (Router.current()) {
    return Router.current().route.getName() === page ? "active" : "";
  }
});

My problem is that when I press my browsers back button, both page1 and page2 link's show up as active.

Any help would be greatly appreciated in solving this.


Solution

  • Without being able to see your route definitions, I would say that you must have a duplicate reference to the first route somewhere in your code. I can definitely for sure say that your global template helper is properly implemented because I define all of my active tab template helpers in the same way that you have defined yours (with only minor syntactical differences).

    For your HTML, everything looks good with the exception of your page 2 anchor tag referencing the wrong route. I would suggest implementing your tags like this to take advantage of an Iron-Router template helper:

    <li class="{{navClassName 'page1'}}">
        <a href="{{pathFor 'page1'}}">Page 1</a>
    </li>
    <li class="{{navClassName 'page2'}}">
        <a href="{{pathFor 'page2'}}">Page 2</a>
    </li>
    

    With your HTML defined in this way, you do not have to update your anchor tag path references if you happen to update your route paths at all. They will change accordingly with the use of the pathFor template helper provided by Iron Router.

    If you could edit your question to include your route definition logic as well, I could help you more in solving this issue.