Reputation: 155
I am having a slight issue in trying to get the "active" class set when I click on the link so that I know which page I am in. Currently what happens is when I click on a different tab it sets it "active" but then goes away when the page is loaded.
I am using Node.js, Express, Handlebar and Bootstrap. I have a feeling it has to do something with the fact that the class="nav-link active" is in the < a > tag instead of the < li > tag?
Please also find a quick video of the issue described:
https://i.sstatic.net/oZ8hU.jpg
thanks in advance!
layout.handlebars
<div class="container">
<div class="header clearfix">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Home App</a>
<ul id="navbarMenu" class="nav nav-pills">
{{#if user}}
<li id="dashboardNav" class="nav-item">
<a class="nav-link active" href="/">Dashboard</a>
</li>
<li id="accountNav" class="nav-item">
<a class="nav-link" href="/users/account">Account</a>
</li>
<li id="logoutNav" class="nav-item">
<a class="nav-link" href="/users/logout">Logout</a>
</li>
{{else}}
<li class="nav-item">
<a class="nav-link" href="/users/login">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/users/register">Register</a>
</li>
{{/if}}
</ul>
</nav>
</div>
<script type="text/javascript">
$('ul.nav-pills li').on("click", "a", function() {
alert("test");
$(this).siblings().removeClass("nav-link active");
$(this).addClass("nav-link active");
//alert($this.child().href);
});
</script>
Upvotes: 4
Views: 2190
Reputation: 461
In the view (handlebars) add if condition:
<a class="nav-link {{#if path "foo"}} active {{/if}}" href="/foo">Dashboard</a>
In the server side (route or controller that render the view) Edit it and pass the path variable:
router.get('/foo', function (req, res, next) {
res.render('foo', { title: 'foo' ,path:"foo",});
});
Do that for each page you want to add active css class for each anchor.
Upvotes: 2
Reputation: 155
The solution was to actually do it on the server side using handlebars {{#if}} block statements and passing the handlebars the appropriate variable from the routes.
Upvotes: 0