Himanshu Yadav Himanshu Yadav - 2 months ago 20
Javascript Question

Meteor: Change the class of link on click

Template:

<template name="header">
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item {{active}}" href="{{pathFor 'homePage'}}">Home</a>
{{#if currentUser}}
<a class="blog-nav-item {{active}}" href="#">{{Meteor.userId}}</a>
{{else}}
<a class="blog-nav-item {{active}}" href="{{pathFor 'loginPage'}}">Login</a>
<a class="blog-nav-item {{active}}" href="{{pathFor 'signUpPage'}}">Sign Up</a>
{{/if}}
<a class="blog-nav-item {{active}}" href="#">About</a>
</nav>
</div>
</div>
</template>


header.js

Template.header.events({
'click a': function(e) {
e.preventDefault();
this.active?"active":"";
}
});


I just want to make set click link's class as
active
. Clicked link class should look like
class="blog-nav-item active"
.

Answer

I guess this would be the "Meteor way" you wanted:

<template name="menu">
    <ul>
        <li class="{{#if isCurrentPage 'pageA'}}active{{/if}}">
            <a href="{{pathFor 'pageA'}}">Page A</a>
        </li>
        <li class="{{#if isCurrentPage 'pageB'}}active{{/if}}">
            <a href="{{pathFor 'pageB'}}">Page B</a>
        </li>
        <li class="{{#if isCurrentPage 'pageC'}}active{{/if}}">
            <a href="{{pathFor 'pageC'}}">Page C</a>
        </li>
    </ul>
</template>
Router.onBeforeAction(function(){
    Session.set('currentRouteName', Router.current().route.name)
})

Template.menu.helpers({
    isCurrentPage: function(pageName){
        return Session.equals('currentRouteName', pageName)
    }
})

Router.current().route.name do evaluate to the current page name in the latest version of iron router, but I don't know if that's part of the public API one should use.

EDIT

Router.current() is apparently reactive, so all JavaScript code you need is the following:

Template.menu.helpers({
    isCurrentPage: function(pageName){
        return Router.current().route.name == pageName
    }
})