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); } }); });
Hello,
thanks for your post, but it doesn’t work for me…
do you have this exemple on a website ?
Thanks
Hi Thierry, I currently have something like this online at http://bbc-news.snaver.net/ . However you may have more luck using jQuery’s Live/Bind resource, see here http://api.jquery.com/live/ .
Good catch! This post helped a lot! 😛
This worked great. Thanks.
A note: append() doesn’t seem to work, but html() does.