Search code examples
javascriptcomponentssvelte

How to highlight the active navbar link in svelte js


Consider I have two components in svelte js one of them is Navbar and the other is NavbarLink. I want to highlight the currently active link in navigation bar. So far I did it using jquery:

$(".navbar").children(".nav-link").click(function(event){
   $(this).addClass("active");
   $(this).siblings().removeClass("active");
})

I am a newcomer to svelte js and still learning the basics. I want to get this kind of behavior in svelte js too. Can anyone tell me what is the best way of doing it?


Solution

  • <script>    
      let tabs = ["one", "two", "three"]
      let selected = tabs[0]
    </script>
    
    //your links
    <li on:click={()=>selected = tabs[0]} class:selected={selected==="one"}>
    <li on:click={()=>selected = tabs[1]} class:selected {selected==="two"}>
    <li on:click={()=>selected = tabs[2]} class:selected={selected==="three"}>
    
    //show if a specific tab is clicked
    {#if selected === "one"}
    ..
    {:else if selected === "two"}
    ..
    {:else}
     ..
    {/if}
    
    <style>
      .active{
         //your css rules for active class
      }
    </style>