I'm trying to set a random image background with css and javascript to a div, but when I load the random image on google chrome it does not work
I tried to do all image urls in variables but this does not work.
does anyone know why it is changing my code and why it is not working
code that loads the random image
<script type="text/javascript">
var image1 = "images/image1.png";
var image2 = "images/image2.png";
var image3 = "images/image3.png";
var image4 = "images/image4.png";
var imageURLs = [
"image1"
, "image2"
, "image3"
, "image4"
];
function getImageTag() {
var img = '<div class="pdiv2" style="background-image: url("';
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img += imageURLs[randomIndex];
img += '")"></div>';
return img;
}
</script>
where the image is printed
<script type="text/javascript">
document.write(getImageTag());
</script>
output when I do with google chrome inspect, edit as html
<div class="pdiv2" style="background-image: url(" image3")"=""></div>
Aucun commentaire:
Enregistrer un commentaire