0

I have a bootstrap button group with few buttons each of them with their a tag that links to a new page. I've added the jquery code for retaining the active state when a button is clicked. The buttons stay active on clicking only if there is no #href. When there is a link and the new page is loaded, the active state is lost. Can someone please help ? I am so lost!

Here is the snippet - html:

<div class="btn-group">
    <a class="btn btn-custom">Home </a> 
    <a class="btn btn-custom" href="/link1"> About us </a>
    <a class="btn btn-custom" href="/link2"> Contact us </a>
</div>

Jquery:

$(".btn-group > .btn").click(function(){
    $(this).addClass("active").siblings().removeClass("active");
});
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Kria
  • 11
  • 1
  • I've also changed these buttons to nav tabs and used this solution for persistent tabs http://aidanlister.com/2014/03/persisting-the-tab-state-in-bootstrap/ but to no avail. Same problem. Active state is lost when the new page is loaded. – Kria Jun 24 '15 at 16:46

2 Answers2

0

I do not know if it is possible to maintain the active state on a new page load.

However, a simple workaround is to apply styling via bootstrap on each page so that the appropriate button appears active. For example if you were on the page link1:

<div class="btn-group">
    <a class="btn btn-custom">Home </a> 
    <a class="btn btn-custom active" href="/link1"> About us </a>
    <a class="btn btn-custom" href="/link2"> Contact us </a>
</div>

This would make the button appear to be active.

nesslerI
  • 1
  • 2
  • Thanks but this makes all buttons active on start. I want them to be active only when they are clicked and the page is loaded. – Kria Jun 24 '15 at 16:45
  • So if I were on the "Home" page you do not want any buttons active. But if I were to click on "link1" you would want the button for link1 to be active when the page loaded correct? – nesslerI Jun 24 '15 at 16:49
  • Yes, thats correct. When I am on link1, page loads, link1 button is active and rest are not active. – Kria Jun 24 '15 at 16:51
  • So to do that you need to go to link1.html page and then paste the code block from my answer into the html page. This should provide the functionality you want. Keep your Home page the same. – nesslerI Jun 24 '15 at 16:52
  • Sorry but I am on drupal 7 with a bootstrap button block that spans across all pages. Thats not possible. – Kria Jun 24 '15 at 16:58
0

This finally worked for me if someone is also looking for a solution. Changed buttons to Nav and lists.

  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');

From Twitter Bootstrap add active class to li

Community
  • 1
  • 1
Kria
  • 11
  • 1