Reputation: 53
I want to load one of the random background image by using jquery. Below is the script I am using and it shows random background on refresh but without fadeIn effect. How can I create fadeIn effect onload. Note: I don't want to cycle random images.
$(document).ready(function() {
var images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg', '06.jpg', '07.jpg', '08.jpg', '09.jpg', '10.jpg'];
$('.about').css({'background-image': 'url(../img/bg/' + images[Math.floor(Math.random() * images.length)] + ')'});
('.about').fadeIn(1000);
});
Upvotes: 1
Views: 4099
Reputation: 13304
$(document).ready(function() {
var images = ['http://funmozar.com/wp-content/uploads/2014/09/Beautiful-Yellow-Birds-06.jpg', 'http://petblaster.com/images/Birdwall.jpg', 'http://www.nscblog.com/wp-content/uploads/2014/04/birds-314989.jpg'];
var url = images[Math.floor(Math.random() * images.length)];
var img = new Image();
img.onload = function(){
$('.about').css({'background-image': 'url('+url+')', 'background-size' : 'contain'});
$('.about').fadeIn(1000);
}
img.src = url;
});
.about{
width: 400px;
height: 400px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="about"></div>
This will preload the image using new Image
. An onload
is attached. When he onload fires it will set the background to the .about
div and fade it in.
I've changed the urls to actually show some results.
Upvotes: 3