Reputation: 1350
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
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
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
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
Reputation: 79032
$("body").on('click', '.close', function() {
$(this).parent().fadeOut();
return false;
});
Upvotes: 0