'How to add an "active" class to navbar in sveltekit?
I'm trying to set path when a route changes, but its not updating:
<script>
import { page } from '$app/stores';
let path;
function getPath() {
path = $page.url.pathname;
console.log(path);
}
$: $page.url.pathname;
$: getPath();
</script>
<aside>
<nav>
<ul>
<li class={path === '/' ? 'active' : ''}>
<a href="/"><img src="/icons/compass.svg" alt="" border="0" />Dashboard</a>
</li>
<li class={path === '/messages' ? 'active' : ''}>
<a href="/messages"><img src="/icons/messages.svg" alt="" border="0" /> Messages</a>
</li>
</ul>
</nav>
</aside>
<style>
nav li.active a {
color: #fff;
}
</style>
THis isn't updating when i change routes in browser.
Solution 1:[1]
let dashboardActive = false;
if(window.location.pathname == '/dashboard'){
dashboardActive = true;
}
<a class="mainmenuNew" href="/dashboard" >
{#if dashboardActive}
<span class="mainmenuImg"><img class='icnImg' src="/leftmenu/dashboard-active.png"></span>
<span class="mainmenutext activemenutxt" >Dashboard</span>
{:else}
<span class="mainmenuImg"><img class='icnImg' src="/leftmenu/dashboard.png"></span>
<span class="mainmenutext" >Dashboard</span>
{/if}
<div style="clear:both;"></div>
</a>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sankar |
