Faizaan Nawaz
Faizaan Nawaz

Reputation: 86

Bootstrap active tab color only changes on one tab

I am trying to set the bootstrap active tab color using Jquery, The problem I am having is when I use my Jquery function it changes the the active tab to red (Great!) but when I click on another tab the color defaults back to the bootstrap blue and the first tab still has the background in red.

Here is the function I was using:

$('document').ready(function () {
    $('.nav-pills>li.active>a').css("background-color", "#FF0000");
})

I need the active color to be set so any tab that is selected will have the color set by me.

Any help would be greatly appreciated.

Upvotes: 0

Views: 2993

Answers (3)

Anurag Kumar
Anurag Kumar

Reputation: 565

Simply use

.nav-pills>li.active>a:focus{background-color: #FF0000 !important;}

Upvotes: 1

Ashish Panwar
Ashish Panwar

Reputation: 1128

Don't set color directly. Which make your code more complicated while switching the tabs. Do it like this:

first create your custom class (or override bootstrap .active):

.my-active-class{
    background-color:red;
}

now toggle this class:

$("#MyTabContainer").click(function(){
  //First remove 'my-active-class'from active tabs
  $(this).find('.my-tab').removeClass('my-active-class');

  //Now finally set 'my-active-class' to this selected tab
  $(this).find('.my-tab').addClass("my-active-class");
});

//add this line to document ready (on page load), to preset the selected tab
$("#MyTabContainer").find('.my-tab').addClass("my-active-class");

That's it.

Upvotes: 0

Tinmar
Tinmar

Reputation: 370

You should run your code every time some item is clicked.

Put $('.nav-pills>li.active>a').css("background-color", "#FF0000"); where you put it, but also in .click or on("click",... event for your tabs to run again and set color again after element with active class is changed.

You could also bind it with .bind().

Also, you should change color for all inactive elements too, after active tab color is set.

Check if there is active class on element, with hasClass("active") and revert colors only on elements which doesn't have class active.

Even better way would be to just addClass and removeClass which contains color property, but you cannot change CSS, as you mentioned.

EDIT:

You could also use .siblings() function, to select all siblings of your selected element and change their color, like this:

$("your-tab-li-element").click(function(){
  $(this).css("background-color", "#FF0000");
  $(this).siblings().css( "background-color", "other-color" );
});

Upvotes: 0

Related Questions