1

I am trying to get the navigation bar focused white when you click on any link.

Here is the code :

$('.navbar li').click(function (e) {
    $('.navbar li.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
    e.preventDefault();
});

As you see that this works fine. Which ever links I click it gets actibve(white) and the others get dark.

But as you can see that e.preventDefault(); prevents the link action. When I get rid of that line then it does full refresh the whole page and then I again lose the active link. Somehow I kind of need to or use ajax to load the page content(Which I do not prefer to do) or Is there any other way?

code-jaff
  • 9,230
  • 4
  • 35
  • 56
akd
  • 6,538
  • 16
  • 70
  • 112

1 Answers1

0

I can think of couple of ways at least to fix this issue

  1. handle it in the client side

    for eg.

    lets assume the url pattern somehow matches the button links, in which case manipulate the url string in javascript to find the corresponding active element and make it's class active

  2. Keep the logic in the server side, and render the UI accordingly -- assuming you might use serverside backend

    for eg. in php

    // set the active element 
    $activeLink = 'link1';
    // when rendering 
    <li class = <?= ($activeLink == 'link1') ? 'active' : '';?> ><a>link1</a></li>
    
code-jaff
  • 9,230
  • 4
  • 35
  • 56