Home > front end >  How to make the corresponding text bold depending on the URL visited/link clicked in ASP.NET Core?
How to make the corresponding text bold depending on the URL visited/link clicked in ASP.NET Core?

Time:02-11

I have this rather primitive issue, but I have no idea how to solve this:

I have a side hierarchy menu in one of many Razor pages and for now I just manually make the current page bold in the HTML.

  • Is there a possibility to automate this?
  • What's the best approach for giving the state of the current page?
  • Does ASP.NET Core have an integrated function/etc for this?

Here's how my side menu looks like:

<div  style="">
      <ul id="menu-map"  style="">
          <li ><a href="/test1" aria-current="page">
            <span>TEST1</span>
          </a></li>        
          <li ><a href="/test2" aria-current="page">
            <span>test2</span>
          </a></li>
          <li ><a href="/test3" aria-current="page">
            <span>test3</span>
          </a></li>
          <li ><a href="/test4" aria-current="page">
            <span>test4</span>
          </a></li>
          <li ><a href="/test5" aria-current="page">
            <span><strong>test5</strong></span>
          </a></li>
      </ul>
</div>

col-sm-2 is a Bootstrap 4 class, yes.

Another ELI5 example:

In the side menu above if I click on TEST1 the TEST1 gets bold text, if I click on test2, test2 gets bold text on that page. (/test1 and /test2 correspondently)

A CSS solution might kind of work, but what if the user gets a link to one of the pages? Hence a pure CSS solution is not viable in my opinion.

CodePudding user response:

Does ASP.NET Core have an integrated function/etc for this?

It seems no such build-in function to achive this client side requirement.

Once you click the link, it will redirect to another page and lose the state of the anchor tag. So you can use localStorage to store the selected anchor tag's index. And add the font-weight: bold class to selected link:

<head>      
    <style>           
          .active{
                font-weight: bold;
            }
    </style>
</head>
<script>
    $(function(){
        var data = localStorage.getItem("index");
        if(data!=null)
        {
            $('ul li').eq(data).addClass('active');
        }
    })
    $("#menu-map").find('a').click(function () {
        var str = $(this).parents("li").index();
        localStorage.setItem("index",str);
    });
</script>
  • Related