Reputation: 459
I'm using Cycle to attempt to cycle through some divs that are generated by another jQuery function. Here's the function:
$.getJSON('../functions.php', function(images) {
$.each(images, function() {
$('#slideshow').append('<div class="slide" style="background-image:url(' + this + ');"></div>');
});
});
I'm having a weird issue. The DIVs are appearing, and if I use the Chrome Inspector I can see them, but they don't show up if I view the source explicitly. Maybe that doesn't matter, but when I run:
$('#slideshow').cycle();
I get an error in the console that says:
[cycle] terminating; too few slides: 0
You can see the site live here: http://new.element17.com
Any idea why this is happening?
Upvotes: 0
Views: 3679
Reputation: 617
To add on to the previous answer, You are making an async request with $.getJSON
So when cycle is being called, no data has yet returned from the request meaning no html has been appended inside 'div#slideshow' so as expected
[cycle] terminating; too few slides: 0
To Fix this: run cycle after the async request is finished. I wouldn't recommend doing a synchronous call
$.getJSON('../functions.php', function(images) {
$.each(images, function() {
$('#slideshow').append('<div class="slide" style="background-image:url(' + this + ');"></div>');
});
$('#slideshow').cycle();
});
Upvotes: 0
Reputation: 3385
The reason for that is that you're populating your slideshow images using getJSON
method.
Even though this method is located before you cycle method, getJSON
is asynchronious method that's why cycle is running before loading images.
Solutions:
1. Use .ajax
instead of .getJSON
with async: false
$.ajax({
async: false,
url: '../functions.php',
success: function() {
$.each(images, function() {
$('#slideshow').append('<div class="slide" style="background-image:url(' + this + ');"></div>');
});
}
});
2 Move $('#slideshow').cycle();
inside .getJSON
method so it run after loading images.
$.getJSON('../functions.php', function(images) {
$.each(images, function() {
$('#slideshow').append('<div class="slide" style="background-image:url(' + this + ');"></div>');
});
$('#slideshow').cycle();
});
This code is not tested
Upvotes: 2