0

I try to understand what it is wrong with my code when I click on my button I change his class but I click again on the changed button class nothing happend I try to use on() function but the same things nothing happend

here my sample code:

$('#my-btn').click(function(){
  $(this).removeClass('btn-success');
  $(this).addClass('btn-danger');
  $(this).html('Close');
});

$('.btn-danger').click(function(){
    alert('hello world');
  $(this).removeClass('btn-danger');
  $(this).addClass('btn-success');
  $(this).html('Open');
});

And my jfiddle for testing : https://jsfiddle.net/aqpdohL2/1/

LuR
  • 251
  • 1
  • 4
  • 16

3 Answers3

1

Try this code. I have checked it. It's working for me.

<div class="section">
  <button class='btn btn-success' id='my-btn'> Open </button>
</div>

$(".section").on("click", "#my-btn", function() {
  $("#my-btn").removeClass('btn-success');
  $(this).addClass('btn-danger');
  $(this).html('Close');
});

$(".section").on("click", ".btn-danger", function() {
  $(this).removeClass('btn-danger');
  $(this).addClass('btn-success');
  $(this).html('Open');
});
Tanmay Patel
  • 1,770
  • 21
  • 28
1

Because when your code runs this selector doesn't match anything:

$('.btn-danger')

So the second click handler is never bound to anything and never invoked, the first one is always invoked.

There's no need for two click handlers here. Your first click handler will be invoked every time you click on the element, so you can just put your logic in that handler. For example:

$('#my-btn').click(function(){
  $(this).toggleClass('btn-success');
  $(this).toggleClass('btn-danger');
  if ($(this).html() === 'Open') {
    $(this).html('Close');
  } else {
    $(this).html('Open');
  }
});

Fiddle

In general it's best not to attach many click handlers to the same element as it becomes more difficult to manage the behavior of your code. Instead, prefer defining the logic in fewer click handlers and managing that logic.

David
  • 208,112
  • 36
  • 198
  • 279
1

@David's solution can be shortened even further:

$('#my-btn').click(function(){ $(this)
    .toggleClass('btn-danger btn-success')
    .html($(this).html()==='Open'?'Close':'Open');
});

The jQuery method .toggleClass() can be applied to multiple class names at the same time.

$('#my-btn').click(function(){ $(this)
    .toggleClass('btn-danger btn-success')
    .html($(this).html()==='Open'?'Close':'Open');
});
.big {font-size:24pt}
.btn-success {background-color:green}
.btn-danger {background-color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="my-btn" class="big btn-success">Open</button>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43