Search code examples
jqueryclickliveunbind

Unbinding live click on live element doesn't work as expected


I have following function to add elements to the page on the fly;

function modalConfirm (title, msgBody, btnOK, btnCancel) {
    element = '<div class="ui-modal-widget"><div class="confirm"><h2>'+title+'</h2><div>'+msgBody+'</div></div>';
    element += '<div class="button-panel" style="float:right; margin-top:-30px; margin-right:5px;">';
    element += '<a href="#" rel="closeModal">'+btnCancel+'</a>';
    element += '<a href="#" rel="confirmModal">'+btnOK+'</a>';
    element += '</div></div>';
    // OPEN MODAL WINDOW

I'm calling the function above when $('a.checkData') is clicked.

PROBLEM


Everything seems working fine except, if I close the opened modal window by clicking $('a[rel=closeModal]') more than once and after that few times click $('a[rel=confirmModal]') it is doing the same actions as many times as I clicked $('a[rel=closeModal]').

Example;

$('a[rel=closeModal]').live('click', function(e) {
e.preventDefault();
// CLOSE MODAL BOX
});

$('a[rel=confirmModal]').live('click', function(e) {
e.preventDefault();
console.log('Modal Is Confirmed');
});

Consider the code above. When $('a.checkData') is clicked and user clicks $('a[rel=closeModal]') 5 times before clicking $('a[rel=confirmModal]'). It will write 5 times Modal Is Confirmed for 1 click. If user clicks $('a[rel=closeModal]') 10 times before clicking $('a[rel=confirmModal]'). It will write 10 times Modal Is Confirmed.

I will be glad if you could help me out with this problem. I tried to add $('a[rel=confirmModal]').unbind('click'); literally everywhere (inside the function, before calling the function, after calling the function just before / after / inside of the $('a[rel=confirmModal]').live('click',function(){}); without any success.

Thank you for your time and concern in advance.


Solution

  • You need to consider using jQuery delegate() and jQuery undelegate()

    This is very similar to live however you can choose whether or not to bind to the document body or to a relative parent of the future added element.