LaLaAsDev
LaLaAsDev

Reputation: 315

is it possible to re-initialize all-plugins for jQuery after ajax call?

If i received ajax response using $.post(...) , $.get(...) or something.

received response is a html format document and includes jQuery plugins.

i know jQuery plugin needs to reinitialize after ajax response. something like this

$.get('<ajaxurl>').done(function(response){
    $('#some_element').html(response);
    $('#element1_in_some_element').init_plug_in_1();
    $('#element2_in_some_element').init_plug_in_2();
    $('#element3_in_some_element').init_plug_in_3();
    $('#element4_in_some_element').init_plug_in_4();
    ....
});

But is it possible to re-initialize all plugins after ajax call?

like this

$.get('<ajaxurl>').done(function(response){
    $('#some_element1').html(response);
    $('#some_element1').init_plug_in_all();
});

!!

Upvotes: 3

Views: 3073

Answers (3)

BenG
BenG

Reputation: 15154

If you want $('#some_element1').init_plug_in_all(); then you could write a plugin.

$.fn.init_plug_in_all = function(plug_1, plug_2, plug_3, plug_4){

  this.each(function() {

    plug_1 && $(this).init_plug_in_1();
    plug_2 && $(this).init_plug_in_2();
    plug_3 && $(this).init_plug_in_3();
    plug_4 && $(this).init_plug_in_4();

  });
};

then use like:-

$('#some_element1').init_plug_in_all(true, false, false, true);
$('.some_class').init_plug_in_all(false, false, true, true);
//etc

Upvotes: 1

Phil
Phil

Reputation: 4069

If you bind to the document, it should allow you to have dynamically added elements on the page which have your plugin automatically applied.

For example

$('.datePickers').datepicker();

will only fire on document load, and any NEW elements with the "datePickers" class will not have the functionality available.

But if you attach like this...

$(document).on('load','.datePickers', function() {
     $(this).datepicker();
});

It will apply to all elements with the datePickers class, even those added via AJAX

Upvotes: 3

Marcos P&#233;rez Gude
Marcos P&#233;rez Gude

Reputation: 22158

If you make a function to initialize the plugins, you can call that function when ajax call ends to reinitialize all your plugins. There aren't nothing standard to this, all depends on your plugins and your initializators. Consider something like this:

var initializePlugins = function() {
  $('selector').datepicker();
  $('selector2').fullcalendar();
  $('selector3').jScrollPane();
};

// when ajax done
$.ajax().done(function() {
  initializePlugins();
});

// when the DOM is ready        
$(document).ready(function() {
  initializePlugins();
});

Upvotes: 1

Related Questions