Sankalp
Sankalp

Reputation: 1350

jQuery fails on DOM element inserted by AJAX

I have wrote a simple jQuery function on class named close.

$(function () {
    $(".close").click(function () {
        $(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
            $(this).slideUp(400);
        });
        return false;
    });
});

Its working well but if I insert new DOM element using AJAX this function fails? Why it is so? Though I know solution that to write same function on page that is inserted through AJAX response. I did it and it's working. Why is it not working globally?

I tried to replace the $(".close").click(function () { with $(".close").on("click", function(event){ but it didn't gave me exact solution of my issue.

Upvotes: 0

Views: 389

Answers (4)

bipen
bipen

Reputation: 36531

that is becuase for click event to work the element should be present in the document...use on delegated event

$(document).on("click",".close",function () {
    $(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
        $(this).slideUp(400);
    });
    return false;
});

adding you click event after ajax success function works but then I prefer to go with the on delegated event (since on in jquery was introduce for this purpose)..

I recommend you to use the closest static parent, than the document itself for better performance...

link to read more about delgated on event

Upvotes: 4

sathish
sathish

Reputation: 800

Did you tried using 'live' method.

$(".close").live('click',function () {
    $(this).parent().fadeTo(400, 0, function () { // Links with the class "close" will close parent
        $(this).slideUp(400);
    });
    return false;
});

Upvotes: 0

user2742648
user2742648

Reputation:

Because jQuery binded click event to elements when DOM was ready. It doesn't watch for new elements matching selectors so any elements added after will not have click event binded to your function. To do this, you must do $('.close').click(...) after AJAX request is finished.

Upvotes: 4

Samuel Liew
Samuel Liew

Reputation: 79032

Use on and fadeOut:

$("body").on('click', '.close', function() {
    $(this).parent().fadeOut();
    return false;
});
  • Also, you do not need to slideUp after fading out, as the element is already hidden.
  • Secondly, the default fade duration is already 400, you do not need to state the speed again.

Upvotes: 0

Related Questions