Anup
Anup

Reputation: 1

Make all JavaScript work as normal on ajax content

I am working on a normal bootstrap theme which contains js slider, popup, text-rotation, masonry boxes etc..

The theme contains all relevant js library and main.js

All of these will load new content via ajax on user specified actions.

Here is the js/ajax for text-rotation: In the example below i have to call the "$('.text-rotation').owlCarousel" in order to make the text-rotation to work properly.


    function getCon(type,id)
    {
        var postData = { id: id, type: type}
        $.ajax({
            url : 'getcontent.php',
            type : 'post',
            data : postData,                
            success : function( resp ) { 
                var cont = $('#cont', resp).html();

                $('#conta').after(cont);

                $('.text-rotation').owlCarousel({
                    loop: true,
                    dots: false,
                    nav: false,
                    margin: 10,
                    items: 1,
                    autoplay: true,
                    autoplayHoverPause: false,
                    autoplayTimeout: 3800,
                    animateOut: 'zoomOut',
                    animateIn: 'zoomIn'
                });
            }               
        });
    }

When not calling "$('.text-rotation').owlCarousel" it simply displays the text in list format.

In order to make the all the ajax load content work properly on all section i.e the slider, popup, etc.. i'll have to find the relevant theme functions and code them all on the respective ajax functions.

Is there any predefined js code which i may call on ajaxComplete so tha all ajax content works normal as it works on page load ??

I tried to call the main.js from "getScript" function inside the ajax success but not working..

Upvotes: 0

Views: 54

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21505

The short answer is: no.

jQuery code acts on the DOM that exists when the code is run; if you add to the DOM later on there isn't any general-purpose way for jQuery code to go back and act on the new elements as though they had been there in the first place.

Your options are

  1. rewrite your code to not depend on event bindings / manipulation of the AJAX-based content -- instead use delegated event bindings on elements that are always present
  2. defer your main code init until after all AJAX calls have completed, so the DOM is already in place when you add your bindings
  3. Write specific code to add necessary event bindings / modify newly added DOM chunks individually, as they're loaded

Upvotes: 1

Related Questions