dimanche 4 février 2018

Random background image for each div with the same class

Sorry if there was a question like this before, but I sincerely couldn't find a satisfying answer.

I would like to apply random background to each div with .item class.

I tried to do this with PHP and CSS, something like this:

<?php
$bg = array('bg1.jpg', 'bg2.jpg', 'bg3.jpg', 'bg4.jpg', 'bg5.jpg' );
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>

.item {
  background: url(example.com/images/<?php echo $selectedBg; ?>);
}

It works, but every div has exactly the same background image (for example bg3.jpg), and I would like each individual div to have different random background (I don't mind if they repeat once in a while).

I tried this:

.item {
background: url(<?php echo "example.com/images/bg".rand(1, 5).".jpg"; ?>)

with the same result.

I suppose I need to use JS (which I have absolutely no experience with) to achieve that. I found a working solution for random background color: http://jsfiddle.net/VXG36/1/

I would like to do exactly the same thing, but with background images.

Could anyone help with the code?

Thank you in advance.




Aucun commentaire:

Enregistrer un commentaire