-1

I need help setting a link as active upon clicking on my html top nav bar.

The nav bar looks like this

   <div class="collapse navbar-collapse pull-left" id="navbar-collapse">
    <ul class="nav navbar-nav">
      <li>
          <a href="{{route('home')}}">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Clients <span class="caret"></span></a>
          <ul class="dropdown-menu" role="menu">
            <li><a href="{{ route('add.consumer') }}">Add New Client</a></li></i></a></li>
          </ul>
      </li>
    </ul>
   </div>

So when i click Home it must highlight Home when i click on Clients it must highlight Clients. I really don't know how to achieve this so any help will be very much appreciated.

Shehzad
  • 337
  • 4
  • 25
Vester
  • 129
  • 3
  • 11

2 Answers2

0

// when any a link click
$('a').click(function(){
    // if already any element in active status remove it
    $('a').removeClass('active');
    // add active status to this one only
    $(this).addClass('active');
    
})
.active{
background-color:red;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="collapse navbar-collapse pull-left" id="navbar-collapse">
    <ul class="nav navbar-nav">
      <li>
          <a href="{{route('home')}}">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Clients <span class="caret"></span></a>
          <ul class="dropdown-menu" role="menu">
            <li><a href="{{ route('add.consumer') }}">Add New Client</a></li></i></a></li>
          </ul>
      </li>
    </ul>
   </div>
SilentCoder
  • 1,970
  • 1
  • 16
  • 21
0

Setting via JS is pretty pointless, since as soon as it redirects and loads the new page, that setting will be forgotten. What you want to do is have PHP check your current route, and assign a class based on that. This can be done via the request()->is() check:

If navigating to myapp.com/home, use the following:

<li class="{{ request()->is('home') ? 'active': '' }}">
  <a href="{{ route('home') }}">
    Home
    @if(request()->is('home'))
    <span class="sr-only">(current)</span>
    @endif
  </a>
<li>

This demonstrates how to use via a ternary operator (best used for in-line statements) and the @if()@endif blade syntax. Just ensure your is() check is matching your route, so ->is("") for Route::get("/", ...);, etc. etc. and PHP will automatically assign the active class and (current) SR element.

Note; there is likely a way to handle this for named routes (like route('home')), but I haven't used named routes much, so I'm not positive on that. Also, might be best to assign the result of request()->is('home') to a variable to avoid repeating code.

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102