Randomly display different versions of an image

I created two versions of an illustration of a letter to be displayed on the contact page of my website. I wanted which version of the image that was displayed to be random and wrote some code to make this happen. I’ll share the code here incase some wants to something similar on their website.

JavaScript:

    <!-- Javascript to display random image-->
    <script>
        var myImages = [
            "image1.png", "image2.png"];
        var length = myImages.length;
        var rand = Math.floor(length * Math.random());
        document.getElementById("randomImage").src = myImages[rand];
    </script>

Note that the two images are stored in the array “myImages” and a variable with the length of this array is used when selecting the random image. This will also work if more than two images are added to the array.

With the JavaScript done the image is displayed with HTML by using the same id used in the JavaScript (randomImage):

<!-- HTML to display the image --> 
<img id="randomImage">

Now it’s random which version of the image someone will see each time they visit my contact page:

Illustration of a German love letter.
The German letter
Illustration of a French love letter.
The French letter