Bennet G. Bennet G. - 1 month ago 6
HTML Question

jQuery Button changes not working

I'm trying to give the button a new content if it's clicked. I also add new classes. That work's perfectly fine on the first click but for some reason the innerhtml ins't changing after clicking a second time on it..
HTML:

<button class="btn btn-warning btn-invisible"><i class="fa fa-eye-slash"></i></button>


jQuery:

$('.btn-invisible').click(function() {
$(this).removeClass('btn-invisible');
$(this).addClass('btn-visible');
$(this).html('<i class="fa fa-eye"></i>');
});

$('.btn-visible').click(function() {
$(this).removeClass('btn-visible');
$(this).addClass('btn-invisible');
$(this).html('<i class="fa fa-eye-slash"></i>');
});


I got this fiddle ready: https://jsfiddle.net/dthee9w6/7/

Would love if someone could help.

Answer

You should use 'on' instead of 'click', so that you can play with dynamically added elements.

$('body').on('click','.btn-invisible',function() {

  $(this).removeClass('btn-invisible');

  $(this).addClass('btn-visible');
  $(this).html('<i class="fa fa-eye"></i>');
});            

$('body').on('click','.btn-visible',function() {


  $(this).removeClass('btn-visible');

  $(this).addClass('btn-invisible');
  $(this).html('<i class="fa fa-eye-slash"></i>');
});

hope it helps.

Comments