Mike Hughes
Mike Hughes

Reputation: 77

Bootstrap button toggle class issue

I'm having a rather frustrating issues i'm not understanding with jQuery and Bootstrap/CSS. As you can see from this jsFiddle . When clicking the blue category button it doesn't apply the new new CSS class but the other button displays it fine, any ideas why this is occurring?

HTML:

<button type="button" class="btn btn-primary" id="btn_IncCat">Category</button>
<button type="button" class="btn btn-success" id="btn_IncCat2">Category</button>

CSS:

.btn-primary {
    color: #fff;
    background-color: #428bca;
    border-color: #357ebd;
}
.btn-success {
    color: #fff;
    background-color: #5cb85c;
    border-color: #4cae4c;
}

jQuery:

$(document).ready(function () {
    $('#btn_IncCat').click(function () {
        //  $('#btn_IncCat').css({ 'background-color': '#5cb85c','border-color': '#4cae4c' })
        $('#btn_IncCat').toggleClass('btn btn-success')
    })
})

Upvotes: 1

Views: 5161

Answers (3)

bto.rdz
bto.rdz

Reputation: 6720

When you use $('#btn_IncCat').toggleClass('btn success') is similar to

if($('#btn_IncCat').hasClass('btn btn-success')) {
    $('#btn_IncCat').removeClass('btn btn-success')
} else {
    $('#btn_IncCat').addClass('btn btn-success')
}

the first problem was that you dont need to remove the btn class, bootstrap uses this class to set the padding, border, border radius, margin and other properties you only wanted to change the color, wich is specified in the class btn-primary so instead of

$('#btn_IncCat').toggleClass('btn btn-success');

do

if ($('#btn_IncCat').hasClass('btn-success')) {
    $('#btn_IncCat').removeClass('btn-success').addClass('btn-primary');
} else {
    $('#btn_IncCat').removeClass('btn-primary').addClass('btn-success');
}

or even better

$('#btn_IncCat').toggleClass('btn-primary btn-success')

here the example http://jsfiddle.net/wLxhj4ht/5/

Upvotes: 4

Jakub Matczak
Jakub Matczak

Reputation: 15656

Ok, this is really simple.

When you do

   $('#btn_IncCat').toggleClass('btn btn-success')

You're switching each class given as the argument. You gave btn and btn-success, so when you click the button, it switches them off.

But you want to keep btn class right? So you should not toggle it. You want to switch btn-primary and btn-success alternately. So you change your code to:

   $('#btn_IncCat').toggleClass('btn-primary btn-success')

http://jsfiddle.net/wLxhj4ht/4/

Upvotes: 4

amtest
amtest

Reputation: 700

html

<button type="button" class="btn btn-success"
id="btn_IncCat">Category</button>

jquery

$(document).ready(function () {
  $('#btn_IncCat').click(function () {
      if($(this).hasClass('btn-primary')){
        $(this).removeClass('btn-primary');
        $(this).addClass('btn-success');
      }else{
        $(this).removeClass('btn-success');
        $(this).addClass('btn-primary');
      }
  });
});

Upvotes: 1

Related Questions