Skip to content Skip to sidebar Skip to footer

How To Re-attach JQuery Functions After AJAX Content Load?

There are a few jQuery UI functions that I call this way: jQuery(document).ready(function(){ jQuery('.accordion').accordion(); }); But my page is AJAX based and some pages may

Solution 1:

You can use the DOMNodeInserted event and check for the accordion class.

document.addEventListener('DOMNodeInserted', function(e) {
    var el = $(e.target);
    if(el.hasClass('accordion')) {
        el.accordion();
    }
});

Example use of DOMNodeInserted: http://jsfiddle.net/qErHs/


Solution 2:

I have a similar issue with jQuery widgets. What I did was use the ajaxComplete method to attach the widgets.

$(document).ajaxComplete(function()
    {
        $(".accordion").accordion();
    });

that way, the function gets called every time an AJAX method is complete and will attach the accordion to any new elements with class accordion


Solution 3:

http://api.jquery.com/on/

"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time."

jQuery(document).on("change", ".accordion", function() {
  jQuery(".accordion").accordion();
});

Solution 4:

You can check for ".accordeon"-length. Just create a function...

function init_accordeon(){
    if($('.accordeon').length) {
        $(".accordon").accordeon();
    }
}

and than call this function after your ajax_calls.


Solution 5:

you can trigger custom events after ajax call.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>on demo</title>
  <style>
  p {
    color: red;
  }
  span {
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>

<script>
$( "p" ).on( "myCustomEvent", function( event, myName ) {
  $( this ).text( myName + ", hi there!" );
  $( "span" )
    .stop()
    .css( "opacity", 1 )
    .text( "myName = " + myName )
    .fadeIn( 30 )
    .fadeOut( 1000 );
});
$( "button" ).click(function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
});
</script>

</body>
</html>

Post a Comment for "How To Re-attach JQuery Functions After AJAX Content Load?"