jQuery function stops working after Ajax search

0

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

I put all HTML for a view. Then I get all the HTML of that view through ajax and feed my page replacing the current content with the new one. I did a 1 minute video showing the error:

link

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

  

Function that stops working

$('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 do not exist and delegate these days and I think there's something to be said about this, can anyone help me solve it. I think I have to change this function so it works on the elements that exist and what will exist.

Well, that's it.

    
asked by anonymous 19.11.2016 / 20:30

1 answer

1

You need to add events to a parent element, which is not changed by ajax after the initial load, 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 only assigned at initial load, so all existing 'a[href^="#"]' will receive the assignments and will work, but then you clean them and replace them with new assignments without this assignment, then the function stops working. But doing the assignment in body , he who will respond for the event and pass on to his children 'a[href^="#"]' both already exist and all new ones created after ...

    
19.11.2016 / 21:46