-2
$(".btn-close").on('click', function () {
    alert('click');
    var win = $(this).closest("div.window");
    var winID = win.attr("id");

    $(win).find("*").each(function () {
        var timerid = $(this).attr("data-timer-id");
        if (timerid != null || timerid != 'undefined') {
            window.clearInterval(timerid);
        }
    });

    if (winID != 'undefined' || id != null) {
        $('#' + winID).remove();
    }
});

So since i'm using .on('click'), I thought this would handle dynamically added items to the dom or is that not correct?

I'm prepending items to an element via ajax when a user clicks a button. but when I click on it to close, the event doesn't fire.

What is the best way to handle this?

CoderPi
  • 12,985
  • 4
  • 34
  • 62
Tsukasa
  • 6,342
  • 16
  • 64
  • 96

1 Answers1

4
$('body').on('click', '.btn-close' , function(){})

take a look at Event binding on dynamically created elements?

Community
  • 1
  • 1
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • 3
    perhaps a comment explaining why/how this works would help – AmmarCSE Nov 25 '15 at 15:58
  • 2
    It is important to note, that delegating at this high of a level in the DOM is completely inefficient. It's better to use the closest parent container (perhaps the one the ajax content is appended to) as the delegated container. Understandably, the OP did not post their HTML structure so this is the best at which we can assume based on the context of the question. – War10ck Nov 25 '15 at 15:59
  • 2
    Thank you. And @War10ck I did change from body to "#mainContentArea" which is in the click function provided. – Tsukasa Nov 25 '15 at 16:02
  • @AmmarCSE you are right I have to explain and War10ck is right to explain that .. but While I explain the question its already duplicated by Tushar .. which explain every single piece for why we using that .. any way I edited my answer with the link to reference .. Thanks :-) – Mohamed-Yousef Nov 25 '15 at 16:09
  • @War10ck thanks for explain :-) – Mohamed-Yousef Nov 25 '15 at 16:12