Search code examples
jqueryclassbuttondetect

jQuery: Detect a click on a changed class name that is NOT the original class


I have this button that changes its class from maximize to minimize. Originally it has a maximize class but on click it changes to a minimize. Now I want to catch the click on minimize and only minimize.

Take a look at my code below:

$('.button-maximize').off('click').on('click', function() {
    $(this).removeClass('button-maximize').addClass('button-minimize');
});

So this will change the class to minimize. Obviously I need event delegation to catch the event.

So I do this next:

$('.button-wrap').off('click').on('click', '.button-minimize:not(.button-maximize)', function() {
    alert('test');
});

To clarify button-wrap is the parent. So my problem is that this alert('test'); fires when I first click on the maximize button. How do I tell jQuery that I only want it to fire if the button doesn't have a class "button-maximize"?

Thank you!


Solution

  • Just use the click either way and check it.

    $('.button-wrap').on('click', '.button-minimize, .button-maximize', function() {
      if ($(this).hasClass('button-maximize')) {
        $(this).removeClass('button-maximize').addClass('button-minimize');
      } else {
        alert('test');
      }
    });
    

    EDIT Response to comment: This does bascially the same thing but the key is the event is attached to the wrapper.

    $('.button-wrap').on('click', '.button-maximize', function() {
        $(this).removeClass('button-maximize').addClass('button-minimize');
    }).on('click', '.button-minimize', function() {
        alert('test');
    });