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...

functioninit_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><htmllang="en"><head><metacharset="utf-8"><title>on demo</title><style>p {
    color: red;
  }
  span {
    color: blue;
  }
  </style><scriptsrc="https://code.jquery.com/jquery-1.10.2.js"></script></head><body><p>Has an attached custom event.</p><button>Trigger custom event</button><spanstyle="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?"