When updating a Div with jQuery or Ajax the components stop working

0

I'm using a template that I found on the internet, when I click on a menu option I update the main content by Ajax but when I want to get a div or open a datepicker , or any other functionality of jquery , it is no longer possible to do any of this in all the html that you load by Ajax .

This is the page that is loaded by default, here you can see that the datepicker works and the collapse of the divs below, but when I charge another HTML by Ajax and I show it already I can not use any of these options.

What I did to solve the collapse of the divs , was to look for the code of javascript that activates that and copy it in a new file in this way:

$(function(){

$(document).ready(function() {
    $('.collapse-link').on('click', function() {
        var $BOX_PANEL = $(this).closest('.x_panel'),
            $ICON = $(this).find('i'),
            $BOX_CONTENT = $BOX_PANEL.find('.x_content');

        // fix for some div with hardcoded fix class
        if ($BOX_PANEL.attr('style')) {
            $BOX_CONTENT.slideToggle(200, function(){
                $BOX_PANEL.removeAttr('style');
            });
        } else {
            $BOX_CONTENT.slideToggle(200); 
            $BOX_PANEL.css('height', 'auto');  
        }

        $ICON.toggleClass('fa-chevron-up fa-chevron-down');
    });

    $('.close-link').click(function () {
        var $BOX_PANEL = $(this).closest('.x_panel');

        $BOX_PANEL.remove();
    });
});

});

That solved that problem, but to be able to make all the functionalities of the template operational, I will have to search the entire template for the code parts of each functionality and add it to my file javascript that I charge with each new page that I open by means of Ajax .

They know some way of being able to solve this without having to load all the javascript each time I load a new page by Ajax .

    
asked by Andrés Pedro Gonzales Rojas 12.06.2017 в 04:44
source

1 answer

0

In principle you are missing information to know what the problem is, anyway I assume that the problem is that the functions js are executed before the elements that execute them are ready, this is because obviously you load the content by Ajax they do not exist at that moment.

If you use Ajax to load content you can use ".done" to print the js you want to run once the Ajax load is finished.

Here is an example:

$.ajax({
 url: 'archivo.php',
 method: 'post', //o get
 data: {xxx}, //en caso de que tengas datos para enviarle al php
 success: function(result){
  //en result tendrás la página cargada para imprimirla en el html.
 }
}).done(function(){
 //aquí insertas todos los scripts que quieres que sean llamados post carga de ajax.
});

Any questions you may have, you can consult, in case you do not understand, I thank you for creating a codepen or jsfiddle with a similar situation to be able to solve it.

Greetings and luck!

    
answered by 06.07.2017 / 17:15
source