Skip to content Skip to sidebar Skip to footer

Jquery Off() Not Removing Click Handler

I have the following code: $(document).ready(function () { EnableModal(); }); function EnableModal() { if (isModalEnabled) { return; } // Initialize modal dialog // attac

Solution 1:

I met this issue before. I wasn't sure what happened at the very beginning and wonder if it was because the selectors weren't actually the same. I checked them and found out they were the same but still couldn't remove the event handler.

I finally fixed this by giving a dummy function as event handler after I removed the original one.

functionDisableModal() {
$('body').off('click', '.modal-link');
$('body').on('click', '.modal-link', () => {});
}

Feel free to use ES5 version if you don't like the lambda expression. as

$('body').on('click', '.modal-link', function(){});

Solution 2:

Works fine here:

var isModalEnabled;

$(document).ready(function () {
  EnableModal();
  $(".disableModal").click(DisableModal);
});

functionEnableModal() {
  if (isModalEnabled) { return; }

  // Initialize modal dialog// attach modal-container bootstrap attributes to links with .modal-link class.// when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
  $('body').on('click', '.modal-link', function (e) {
    e.preventDefault();
    $(this).attr('data-target', '#modal-container');
    $(this).attr('data-toggle', 'modal');
  });

}

functionDisableModal() {
  $('body').off('click', '.modal-link');
}
body { font-family: sans-serif; }
[data-target='#modal-container'] {
  font-weight: bold;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>Click a few "Modal Link" buttons, and watch the button text turn bold.  Then click the "Disable Modal" button, and click the remaining "Modal Link" buttons.  The button text does <em>not</em> turn bold.</p><buttonclass="modal-link">Modal Link</button><buttonclass="modal-link">Modal Link</button><buttonclass="modal-link">Modal Link</button><p><buttonclass="disableModal">Disable Modal</button></p><buttonclass="modal-link">Modal Link</button><buttonclass="modal-link">Modal Link</button><buttonclass="modal-link">Modal Link</button><p>To reset, click the "Run code snippet" button above.</p>

Solution 3:

Without knowing the real cause of this, maybe the solution is to use namespaced events.

$('body').on('click.modal', '.modal-link', function (e) { });

and to remove it

$('body').off('.modal');

But I have a feeling it has nothing to do with this, but with the real issue is with the bootstrap modal. Maybe you need to clean up those attributes.

$('[data-toggle="modal"]').removeAttr("data-target data-toggle");

Post a Comment for "Jquery Off() Not Removing Click Handler"