TrtG
TrtG

Reputation: 2848

JQuery events not always firing

I'm working on a full AJAX app. When I load a new AJAX element, I use callbacks to set handlers on it. To be sure not to be trying to bind a non yet exisiting element, I put the listener on some parent. For example I do this :

$el.on( 'click',"#popin a.closePopin", function(e) { 
        e.preventDefault();
        closePopin(); 
});

This works... 80% percent of time.

My question is, what about the other 20% when nothing is fired?

Thanks.

EDIT : After reading the first answer and comment, I want to precise that the issue is happening randomly on the same elements without updating the code. And $el is a fixe container which never changes or disapear, also the ajax content is necessarly descendant of it.

Upvotes: 0

Views: 784

Answers (1)

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

To avoid this you should not attach the delegated event to $el thus making only descendant elements matching the selector fire the event but rather attach it to document.

$(document).on('click', "#popin a.closePopin", function(e) { 
    e.preventDefault();
    closePopin(); 
});

Upvotes: 1

Related Questions