jQuery Function crashes after Ajax search

Asked

Viewed 118 times

0

I made a system in Codeigniter that searches in real time. In my search, send the parameters via Ajax to the controller and do the query.

I send all the HTML to a view. Then I take all the HTML from this view by ajax and feed my page by replacing the current content with the new one. I made a 1 minute video showing the error:

https://www.youtube.com/watch?v=bRkY3JwBV-0

The mistake is that the Function that I did show/hide content (by clicking on the image) works before Ajax but does not work after Ajax that disappears with the current content and feeds the div with new content.

Function that ceases to function

$('a[href^="#"]').bind("click", function(event){

    event.preventDefault();

    var the_id = $(this).attr("href");

    $(".detalhes").addClass('hide');

    $("div"+the_id+"").parent(".detalhes").removeClass('hide');

    $(".theblog ").removeClass("hide"); 

    $(this).parents(".theblog").addClass("hide");

    $('html, body').animate({ scrollTop:$(the_id).offset().top-25}, 'slow');
});

I was studying about elements that don’t exist and delegate these days and I think it has something to do with that matter, will someone help me to solve. I think I have to change this function to work in the elements that exist and that will exist.

Well, that’s it.

1 answer

1


You need to add the events into a parent element, which is not changed by ajax after the initial upload, something like:

$("body").on("click", 'a[href^="#"]', function(event){

    event.preventDefault();

    var the_id = $(this).attr("href");

    $(".detalhes").addClass('hide');

    $("div"+the_id+"").parent(".detalhes").removeClass('hide');

    $(".theblog ").removeClass("hide"); 

    $(this).parents(".theblog").addClass("hide");

    $('html, body').animate({ scrollTop:$(the_id).offset().top-25}, 'slow');
});

Think of it as follows, events are assigned only on the initial load, so all 'a[href^="#"]' existing assignments will receive and will work, but then you clean them and replace them with new ones without this event assignment, then the function ceases to work. But doing the assignment on body, he who will answer for the event and pass on to his children 'a[href^="#"]' both those that already exist and all new ones that are created after...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.