0

The following code adds data to the container #section via ajax:

$(".btnGetImages").click(function(event){
    event.preventDefault();

    // get id of article
    var id = $(this).attr('data-id');

    // get images via ajax
    $.ajax({
        url: "includes/get_images.php",
        type: "get",
        data: {article:id},
        success: function(data) {
            // insert data into container
            $("#section").html(data);
        },
        error:function() {
            $("#section").html('show error msg here...');
        }
    });
});

Inside the container #section there are elements with a class .thumb that i would like to click. For some reason, the click doesn't trigger, even though i added the .on event correctly. Why?

$(".thumb").on("click", function(event) {
    alert('yo, im a thumb...');

    event.preventDefault();
});
Marco
  • 2,435
  • 4
  • 35
  • 56
  • Event delegation..... – dsgriffin Apr 10 '14 at 00:36
  • @null: i've read about delegation, but it says delegate() has been superseded by the .on() method... – Marco Apr 10 '14 at 00:38
  • So did you read about how to do event delegation with `on()`? Apparently not, because that's not what you wrote. – Barmar Apr 10 '14 at 00:38
  • http://stackoverflow.com/questions/12207033/jquery-on-event-doesnt-work-for-dynamically-added-element – Lin Apr 10 '14 at 00:38
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Barmar Apr 10 '14 at 00:39
  • These answers aren't even anywhere near accurate. You need to re-bind event listeners to **dynamically generated content** which means you need to re-specify any .delegate or .on or .whatever functions used. – Justin Mitchell Apr 10 '14 at 00:41

2 Answers2

1

Because they were dynamically created, you need to use event delegation. Use '#section' as the selector, as it's more efficient than using document:

$("#section").on("click", ".thumb", function(event) {
    event.preventDefault();
    alert('yo, im a thumb...');
});
dsgriffin
  • 61,907
  • 17
  • 128
  • 134
1

Because you need to re-apply any event handlers to any dynamically generated code.

function foo() {
    alert('foo');
}

$('body').html('<p>something in here</p>');
$('body p').on('click', foo);

The best way is to pre-define a function and then assign it as your event handler. When jQuery is loaded it runs through the HTML code and assigns any defined event handlers to any HTML code that exists. If you add to the document, the event listeners don't exist, so you need to re-apply them.

Justin Mitchell
  • 319
  • 1
  • 5