JQuery doesn't work after Ajax Refresh

I have this code inside a webblock Javascript Property:

$(document).ready(function() {
    
$(".item2-1").click(function() {
    $('html,body').animate({
        scrollTop: $(".index2-2").offset().top - 60},
        'slow');
});

});

 and after I do Ajax Refresh for that item, it doesn't work anymore!


Does anyone have a solution for that?



Hi Mohamed,

The click event gets lost because the refreshed element is "new" to the DOM on the page. Have you tried setting the click event with the "on" method?

Something like this:

$("html").on("click", ".item2-1", function() {
    $('html,body').animate({
        scrollTop: $(".index2-2").offset().top - 60},
        'slow');
});

Afonso Carvalho wrote:

Hi Mohamed,

The click event gets lost because the refreshed element is "new" to the DOM on the page. Have you tried setting the click event with the "on" method?

Something like this:

$("html").on("click", ".item2-1", function() {
    $('html,body').animate({
        scrollTop: $(".index2-2").offset().top - 60},
        'slow');
});


Yes, I tried it but it's not working as well!

Solution

How about rerunning the Javascript once your Ajax refresh runs? You could encapsulate your logic like this:

function itemClickEvent() {
$(".item2-1").click(function() {
    $('html,body').animate({
        scrollTop: $(".index2-2").offset().top - 60},
        'slow');
});
}
$(document).ready(function() {
    itemClickEvent();
});

And then in your refresh logic you could rerun your event logic to make sure it gets set to the new elements with the RunJavascript action:

Solution

Afonso Carvalho wrote:

How about rerunning the Javascript once your Ajax refresh runs? You could encapsulate your logic like this:

function itemClickEvent() {
$(".item2-1").click(function() {
    $('html,body').animate({
        scrollTop: $(".index2-2").offset().top - 60},
        'slow');
});
}
$(document).ready(function() {
    itemClickEvent();
});

And then in your refresh logic you could rerun your event logic to make sure it gets set to the new elements with the RunJavascript action:

Thanks Afonso, that worked!


Nice. I could've sworn the on method worked for new elements, but I guess not. Glad you got it sorted out.