Reputation: 609
I currently have some php that changes the background image of a div everytime the page is refreshed.
In the head of my HTML I have this
<?php
$bg = rand(1, 6);
$bgchange = $bg.".jpg";
?>
and then this
<style type="text/css">
.cover {
background-image: url('../img/backgrounds/<?php echo $bgchange; ?>');
}
</style>
As you can see this is a very simple bit of php it does do the job but I am having problems when the site is first loaded on a computer or if the internet is slow where the image fails to load.
Any javascript guys that can recommend a solution to this I would greatly appreciate, I'm also thinking javascript will be better as the image can 'fade' in etc. I am referencing jquery-1.10.2 in my project.
P.S. Solution does not have to be javascript if anyone knows how to improve my php code or can offer a reason why the code fails sometimes, that would be really helpful.
Upvotes: 0
Views: 11717
Reputation: 24703
First create an array of images:
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
Then, set a random image as the background image:
$('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
That should work no problem.
Upvotes: 3
Reputation: 2216
you can do (and should) do this action in js.
on the document load function you can do this. //document load function
$(function(){
var bgImage = (Math.floor(Math.random() * 6))+ ".jpg;"
$('.cover').css('background-image',"../img/backgrounds/"+bgImage);
});
and this way you can keep using the folders you are using and not change anything.
Upvotes: 2