vendredi 26 novembre 2021

How to get a random image when we reload the HTML browser ? using javascript, css and html

I've checked answers on this topic and I tried a bunch of them but still doesn't work for me. I would like that a different image appears when I reload my HTML page.

For now, I have this code that is quite simple :

HTML :

<head>

<script type="text/javascript" src="../src/index.js"></script>

</head>

<body>
  <div id="container">
    <img id="image_shower_vehicule" class="vehicule" />
  </div>
</body>

</html>

CSS :

#container{
    position:relative;
    width:400px;
    height:400px;
    margin-left: auto;
    margin-right: auto;
    background-color: black;
    z-index:0;
}

.vehicule {
  position:absolute;
  z-index: 1;
}

JS :

var images_array_vehicule = ['vehicule1.png','vehicule2.png','vehicule3.png'];

function getRandomImagevehicule() {

random_index_vehicule = Math.floor(Math.random() * images_array_vehicule.length);
selected_image_vehicule = images_array_vehicule[random_index_vehicule];
document.getElementById('image_shower_vehicule').src =`../public/layers/vehicule/${selected_image_vehicule}`;

}

I have the following folders directory...: https://i.stack.imgur.com/xtnML.png

Any ideas that could help me ?

The future step is to do the same thing with different layers and overlay the chosen images with z-index but for now I just want to have a random image when I reload the page.

Thanks for your help !




Aucun commentaire:

Enregistrer un commentaire