LaurentG
LaurentG

Reputation: 472

jQuery on click event is lost after DOM updated by ajax call

I have something working, but as I'm not a so used to code in JS, I don't know if it's the right way to do it.

I have a simple:

<div class="offers"></div>

And by calling myUrl, I retrieve ready to use HTML (some .offer div) that I then append to the .offers div. But I want to have a click event on these freshly appended .offer

$.ajax({
    'url': myUrl,
    success: function(data){
        offers.append(data);
        $('.offer').on('click', function(e) {
            e.preventDefault();
            $('.offers .offer').removeClass('selected');
            $(this).addClass('selected');
        });
    }
});

Thank you for your expertise !

Upvotes: 0

Views: 2428

Answers (2)

maxime_039
maxime_039

Reputation: 494

You can simply try that:

$(document).on('click', '.offers .offer', function(e) {
    // Code here
});

Ideally, for performance purpose, replace document by the nearest ID on your DOM.

UPDATE: After a comment from A. Wolff, I removed the "document.ready" not needed here. (please read comment).

Upvotes: 5

Mark Schultheiss
Mark Schultheiss

Reputation: 34168

Put the event handler outside the ajax:

$.ajax({
    'url': myUrl
}).done(function(data){
    var offers = $('.offers');
    offers.append(data);
});
$('.offers').on('click','.offer' function(e) {
   e.preventDefault();
   $('.offers').find('.offer').removeClass('selected');
   $(this).addClass('selected');
});

Upvotes: 1

Related Questions