[SOLVED] Nav Links Using Flow Router have to be clicked twice to get background color to change


i have setup a navigation template for my header. I have also set it so that when the click event is detected, it should change that element to active, and thus the background color of that nav element to green.

I have it working, except that when I click, I think ti changes, but then routes to the new page / template, and refreshes, so the nav elements immediately go back to no difference in background color. It happens so fast that I can’t see it to confirm, but that’s what I believe is happening. I believe this, because once the navigation is done, I can re-click the nav element, and the background color takes, and remains until I click a new nav element.

I tried event.preventDefault() in my event class for the nav template, and the color changes with a single click, but my pages stop routing.

So, how do I get the nav background to change with a single click, and the router to work properly as well?

Here is my code for this part.

HTML / Template for navigation:
<template name="headerNav"> <header> <ul> <li><a id="home" href="/">Home</a></li> <li><a id="addNotification" href="addNotification">Add Notification</a></li> <li><a id="manageUsers" href="manageUsers">Manage Users</a></li> <li style="float:right"><a id="about" href="about">About</a></li> </ul> </header> </template>

Template Event
Template.headerNav.events({ 'click li' (event) { var clickedTarget = event.target.id; $('a').removeClass('active'); document.getElementById(clickedTarget).className += " active"; },

.active { background-color: #4CAF50; }

Any help is greatly appreciated.


Using event.preventDefault() is the way to go.

In your click handler, prevent the default event from bubbling. Your route should stop, as you noted.

The next thing to do is perform your cosmetic changes.

Then, when you’re ready, tell FlowRouter to set the path of the browser to your desired destination:


Edit: this should bein the flow router docs: https://github.com/kadirahq/flow-router


Indeed it is. I wasn’t even using FlowRouter to change the page I suppose. I was just using the normal href to get that done, and didn’t realize it.

Now I’m using FlowRouter, as described above at the end of my click event, but still the change is wiped until I click a second time. And, based on your suggestion I changed my order of operations so that FlowRouter renders with BlazeLayout, then I change my background color.

Everything works perfectly. thank you so much.