Reputation: 167
I am trying to show some random images in a div. My HTML code is like this:
<div class="sponsors">
<div id="sponsorsContent">
<div class="spacer"></div>
<div class="sponsorSlide" id="imgageSlide_1">
<img alt="" src="<?php echo $this->baseUrl(); ?>/img/Sponsors/img_1.jpg" /><br />
<span class="thumbnail-text">Image Text</span>
</div>
<div class="spacer"></div>
<div class="sponsorSlide" id="imgageSlide_2">
<img alt="" src="<?php echo $this->baseUrl(); ?>/img/Sponsors/img_2.jpg" /><br />
<span class="thumbnail-text">Image Text</span>
</div> ... </div></div>
I am trying to first shuffle "sponsorSlide" divs and then select 7 of them randomly. I want to show it with fadeIn and fadeOut. Generally, I'm trying this code:
$('#sponsorsContent').addClass('horizontal');
$('#sponsorsContent div').addClass('hidden').removeClass('visible');
$('#sponsorsContent .sponsorSlide').rand(7).removeClass('hidden');
setInterval(function(){
$('#sponsorsContent').fadeOut(500);
$('#sponsorsContent .sponsorSlide').delay(500).addClass('hidden').removeClass('visible').shuffle();
$('#sponsorsContent .sponsorSlide').rand(7).removeClass('hidden').addClass('visible');
$('#sponsorsContent').fadeIn(1500);
}, 5000);
The main problem is, when the code runs, exactly before the div fades out, you can see that the images are changing! But I want to randomize them when they are not visible! I used different ways:
FYI, I am trying to have this concept:
1- showing some random images 2- fade out 3- shuffle images 4- Select 7 random divs 5- fade in 6- go 2
Does anybody have any idea that what is my main mistake? Am I doing something in a wrong way? I got confused and I really want to find out, which way I should try and how I can manage it to work as the way I want?
ps: It does work without fadings! But I need to fade them in and out.
Upvotes: 6
Views: 241
Reputation: 5565
You should be using a callback function in order to prevent the change from showing. If you want to hide -> change -> show, you should do it like this:
$('#image_div').fadeOut(500, function() { //first fade out!
$('#image_div img').attr('src', 'image.jpg'); //only then change the picture
$('#image_div').fadeIn(500); //and fade in
});
What comes in the function(){//code}
will happen ONLY when the fadeOut()
is finished.
Upvotes: 5