user9127206
user9127206

Reputation:

Jquery - How do I change my classes in per click

I want to change my button classes when users clicked "share" button. For that, I'm using toggleClasses()method.

But when I tried, it gives me only last class. Where do I mistake and how can I fix that ?

$('#fb_button').each(function () {
        var count = 0;
        var thisButton = $(this);
        thisButton.click(function () {
            count++;
            thisButton.val("Share" + '(' + count + ')');
            thisButton.toggleClass('green-button blue-button red-button')
        })

})

Upvotes: 0

Views: 43

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Do it like below:-

var array = ['green-button', 'blue-button', 'red-button'];
var count = 0;
$('#fb_button').click(function () {
  if(count==3){
    count = 0;
  }
  $(this).removeClass().addClass(array[count]);
 count++;
});
.green-button{
  background:green;
}

.blue-button{
  background:blue;
}

.red-button{
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="fb_button">Click Me!</button>

Upvotes: 2

Related Questions