18

I have a html as sidebar, and use Bootstrap.

<ul class="nav nav-list">
    <li class="active"><a href="/">Link 1</a></li>
    <li><a href="/link2">Link 2</a></li>
    <li><a href="/link3">Link 3</a></li>
</ul>

I want to do some thing:

When I click a link such as Link 3, the page content will change to Link 3's content, and the Link 3 will have class active, and remove the active clss in Link 1.

I think this can be implemented in jQuery, and I have searched many question in SO, such as:

I use this script:

$(document).ready(function () {
    $('.nav li').click(function(e) {

        $('.nav li').removeClass('active');

        var $this = $(this);
        if (!$this.hasClass('active')) {
            $this.addClass('active');
        }
        //e.preventDefault();
    });
});

But most of them use preventDefault, this will prevent the continued action. So it can't change to Link 3's page content.

If I remove the preventDefault statement, when the page load Link 3's content, the active class will back to Link 1.

So Is there any way to solve this problem?

Community
  • 1
  • 1
Tanky Woo
  • 4,906
  • 9
  • 44
  • 75
  • Why you want to remove `preventDefault()`? it will execute the code written after `preventDefault()` Don't worry about that. – Dhaval Marthak Jul 31 '13 at 16:36
  • @DKM , Yes, I have remove `preventDefault()`, but this will load the Link 3, and the active will back to Link 1. – Tanky Woo Jul 31 '13 at 16:40
  • After every link add a hash (/#link1) and read it through javascript and then set the condition in your code. it will solve your problem. – S. Rasel Jul 31 '13 at 16:50

13 Answers13

32

You are binding you click on the wrong element, you should bind it to the a.

You are prevent default event to occur on the li, but li have no default behavior, a does.

Try this:

$(document).ready(function () {
    $('.nav li a').click(function(e) {

        $('.nav li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • 2
    But when I click the link, the page doesn't load by preventDefault. – Tanky Woo Jul 31 '13 at 17:02
  • It's a little bit unclear what you are asking.Dont you load the page with javascript after the click? If no, you should use javascript to do what you are asking, but your server side language. – Karl-André Gagnon Jul 31 '13 at 17:25
  • @TankyWoo Same thing here. – user2824371 Feb 12 '18 at 17:11
  • @Karl-AndréGagnon..what he is trying to say is that the class is showing active but the content is not displaying...say,Link 2 is showing active but the contents of the link2 is not displaying... – chetan Jul 31 '18 at 11:05
10

I am using bootstrap navigation

This did the job for me including active main dropdown's and the active children

$(document).ready(function () {
        var url = window.location;
    // Will only work if string in href matches with location
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');

    // Will also work for relative and absolute hrefs
        $('ul.nav a').filter(function () {
            return this.href == url;
        }).parent().addClass('active').parent().parent().addClass('active');
    });
Fazil Khan
  • 101
  • 1
  • 2
6

guys try this is a perfect answer for this question:

<script>
    $(function(){
        $('.nav li a').filter(function(){return this.href==location.href}).parent().addClass('active').siblings().removeClass('active')
        $('.nav li a').click(function(){
            $(this).parent().addClass('active').siblings().removeClass('active')    
        })
    })
    </script>
  • This works fine only when I click on the link. But when I go one page back, the `active` class stays with the previous link. How to avoid that? – Pritalgo Jan 01 '22 at 08:16
4

I had the same issue before. Try this answer here, it works on my site.

$(function(){
  var current_page_URL = location.href;
  $( "a" ).each(function() {
     if ($(this).attr("href") !== "#") {
       var target_URL = $(this).prop("href");
       if (target_URL == current_page_URL) {
          $('nav a').parents('li, ul').removeClass('active');
          $(this).parent('li').addClass('active');
          return false;
       }
     }
  });
});

Source: It was original posted here how to set active class to nav menu from twitter bootstrap

Community
  • 1
  • 1
hsusyh
  • 61
  • 3
3
<script type="text/javascript">
$(document).ready(function(){
    $('.nav li').click(function(){
        $(this).addClass('active');
        $(this).siblings().removeClass('active');

    });

});

Milan
  • 31
  • 1
2

If you change the classes and load the content within the same function you should be fine.

$(document).ready(function(){
    $('.nav li').click(function(event){
        //remove all pre-existing active classes
        $('.active').removeClass('active');

        //add the active class to the link we clicked
        $(this).addClass('active');

        //Load the content
        //e.g.
        //load the page that the link was pointing to
        //$('#content').load($(this).find(a).attr('href'));      

        event.preventDefault();
    });
});
Daniel Apt
  • 2,468
  • 1
  • 21
  • 34
0

If you are using server side code like Java then you need to return active tab name and on return page have some function to disable( meaning remove active class) all tabs except the one you returned.

This would require you to add id or name to each tab. Little bit more work :)

BatBold
  • 21
  • 1
  • 5
0
$(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
        $(this).removeClass("active");
    }
    $(this).addClass("active");
});

This is what I came up with. It checks if the "li" element has the class of active, if it doesn't it skips the remove class part. I'm a bit late to the party, but hope this helps. :)

0

You can use cookies for save postback data from one page to another page.After spending a lot time finally i was able to make this happen. I am suggesting my answer to you(this is fully working since I also needed this).

first give your li tag to valid id name like

<ul class="nav nav-list">
    <li id="tab1" class="active"><a href="/">Link 1</a></li>
    <li id="tab2"><a href="/link2">Link 2</a></li>
    <li id="tab3"><a href="/link3">Link 3</a></li>
</ul>

After that copy and paste this script. since I have written some javascript for reading, deleting and creating cookies.

 $('.nav li a').click(function (e) {
  
        var $parent = $(this).parent();
        document.cookie = eraseCookie("tab");
        document.cookie = createCookie("tab", $parent.attr('id'),0);
 });

    $().ready(function () {
        var $activeTab = readCookie("tab");
        if (!$activeTab =="") {
        $('#tab1').removeClass('ActiveTab');
          }
       // alert($activeTab.toString());
       
        $('#'+$activeTab).addClass('active');
    });

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Note: Make sure you have implmeted according to your requirement. I have written this script according to my implementation and its working fine for me.

Rajput
  • 2,597
  • 16
  • 29
0

This will do the trick

 $(document).ready(function () {
        var url = window.location;
        var element = $('ul.nav a').filter(function() {
            return this.href == url || url.href.indexOf(this.href) == 0;
        }).addClass('active').parent().parent().addClass('in').parent();
        if (element.is('li')) {
            element.addClass('active');
        }
    });
Martin Mbae
  • 1,108
  • 1
  • 16
  • 27
0

html code in my case

<ul class="navs">
   <li  id="tab1"><a href="index-2.html">home</a></li>
   <li id="tab2"><a href="about.html">about</a></li>

   <li id="tab3"><a href="project-02.html">Products</a></li>

   <li id="tab4"><a href="contact.html">contact</a></li>
 </ul>

and js code is

  $('.navs li a').click(function (e) {
        var $parent = $(this).parent();
        document.cookie = eraseCookie("tab");
        document.cookie = createCookie("tab", $parent.attr('id'),0);
 });

    $().ready(function () {
        var $activeTab = readCookie("tab");
        if (!$activeTab =="") {
        $('#tab1').removeClass('ActiveTab');
          }
       // alert($activeTab.toString());

        $('#'+$activeTab).addClass('active');
    });

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
0

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$(document).ready(function () {
        var url = window.location;
        $('ul.nav a[href="' + url + '"]').parent().addClass('active');
        $('ul.nav a').filter(function () {
            return this.href == url;
        }).parent().addClass('active').parent().parent().addClass('active');
    });
    
    This works perfectly
0

<ul class="nav nav-list">
    <li id="tab1" class="active"><a href="/">Link 1</a></li>
    <li id="tab2"><a href="/link2">Link 2</a></li>
    <li id="tab3"><a href="/link3">Link 3</a></li>
</ul>