play random video on each visit/refresh with iFrame javascript

How do I create a random video to play every time a user visits/reloads the page with Javascript?

For example, if one person were to go onto my domain, the iFrame would try to load any of the .mp4 files inside of my media file directory where it has like 4 different .mp4 videos. Here is my code below.


    <source src="assets/media/lofi.mp4" type="video/mp4" />
    <script type="text/javascript">
      const video = document.currentScript.parentElement;
      video.volume = 0.15;

      function pause_resume() {
        const button = document.getElementById("pause_resume_button");

        if (video.paused) {

          button.textContent = "resume video";
        } else {
          button.textContent = "pause video";


You need to use Math.random to choose a random video from a list. Then add the chosen video url to the html element, and trigger the “play” event.

const videos = ["video1.mp4", "video2.mp4", /* ... */ "video30.mp4"]
const randomNumber = Math.floor(Math.random() * videos.length)
const currentVideo = videos[ randomNumber ]

const videoElement = document.getElementById('video');
videoElement.src = currentVideo

Related question: changing source on html5 video tag

Source: stackoverflow