Michael Giovanni Pumo
Michael Giovanni Pumo

Reputation: 14784

jQuery: Use a plugin on a page pulled in via AJAX

I'm building a simple AJAX driven website (because of the audience, it's okay to do this) where pages are pulled in based on the anchor etc. Simple enough.

However, one of the pages I want to pull in should have a slideshow on it. Once the call is successful and the page appears, the plugin isn't working.

Do I have to re-initialize the plugins I want to use on a page that's dynamically pulled in?

I can't show any code right now but in theory, what would the best practice be to use plugins and re-init JS code on dynamic pages?

I usually have all my script in one jquery.scripts.js file in the head of the main index page. Do these scripts need to be on the separate pages themselves?

Many thanks! Michael.

$('#logo a').click(function() {

    $.ajax({

        type: "POST",
        url: "./ajax/test.html",
        data: '', 
        dataType: "html",
        success: function(data){

            if(parseInt(data)!=0) {

                $('#cycle').html(data);

                $("#cycle").cycle({

                    fx:         'fade',
                    //easing:   'easeOutExpo',
                    speed:      3000, 
                    //timeout:  0, 
                    //next:     '#cycle-next', 
                    //prev:     '#cycle-prev'

                });

            }

        }

    });

    return false;

});

This code executes the call, loads the page, but does not re-init the plugin. It does nothing, and there are no errors. Weird.

Upvotes: 0

Views: 820

Answers (2)

EssCeeUK
EssCeeUK

Reputation: 251

You don't say whether the cycle plugin has been previously initialized before running the $.ajax command. If it been, then you'll need to destroy the cycle slideshow and re-initialize it.

success:function(data){
    if(parseInt(data)!=0) {
        $('#cycle').html(data);
        $('#cycle').cycle('destroy');
        $("#cycle").cycle({
            fx:'fade',
            //easing:'easeOutExpo',
            speed:3000,
            //timeout:0,
            //next:'#cycle-next',
            //prev:'#cycle-prev'
        });
    }
}

Upvotes: 1

jeffreydev
jeffreydev

Reputation: 1722

What you should do is after you retrieved the ajax page, insert it into your website and when that is done you can initialize the slideshow.

so basically:

$.ajax({
    url: 'myurl',
    success: function (data) {
        $('#target').html(data);
        $('#target .slideshow').slideshow();
    }
});

<div id="#target">
    <div class="slideshow"></div>
</div>

Upvotes: 1

Related Questions