Applying jCarousel to ajax Loaded Content

If you’re working with jQuery and the jQuery plugin jCarousel you may have come across this problem if you try to implement jCarousel on an element where the elements childs aren’t present at page load.

What I was trying to do was to apply jCarousel to a <ul> element and have the <li> element be loaded in via Ajax after the page had finished loading. As a rough example of my markup:

Javascript

$(document).ready(function () {
    $.ajax({
        url: 'http://www.example.com/article/123',
        success: function(data) {
            // Append the returned result to a specefied element
            $('ul').html(data);
        }
    });
    // Setup jcarousel on the ajax target
    $('ul').jcarousel();
});

HTML

<ul></ul>

The Fix

But for one reason or another this doesn’t work, and jCarousel wont initialise on the element, my guess is that it needs all of the mark up at page load in order to load correctly. So to fix this you just need to move the jCarousel initialisation code to the success method of the ajax call, like bellow:

$(document).ready(function () {
    $.ajax({
        url: 'http://www.example.com/article/123',
        success: function(data) {
            // Setup jcarousel on the ajax target
            $('ul').jcarousel();
            // Append the returned result to a specefied element
            $('ul').html(data);
        }
    });
});

code

4 responses to “Applying jCarousel to ajax Loaded Content”

  1. Thierry says:

    Hello,

    thanks for your post, but it doesn’t work for me…
    do you have this exemple on a website ?

    Thanks

  2. Mark says:

    Good catch! This post helped a lot! 😛

  3. John says:

    This worked great. Thanks.

    A note: append() doesn’t seem to work, but html() does.

Leave a Reply