How to randomly load html file inside a html page on page load using javascript?

25 Views Asked by At

I"m trying to get a set of html files (with images with links) to randomly show on the sidebar of a site. I can get the name of the file to randomly show using this code:

function displayRandomMessage() {
  var contentArea = [
      '/includes/side2.htm',
      '/includes/side3.htm',
      '/includes/side4.htm'
  ];

  var randomIndex = Math.floor(Math.random() * contentArea.length);
  var randomMessage = contentArea[randomIndex];

  var messageElement = document.getElementById("contentArea");
  messageElement.innerHTML = randomMessage;
}

And putting this at the end of the page(s):

<script>
    window.onload = displayRandomMessage;
</script>

I'm just not having much luck getting the actual html file to display.

Any help or point in the right direction would be greatly appreciated!

1

There are 1 best solutions below

0
Konrad On

You can use fetch to fetch the html

async function displayRandomMessage() {
  var contentArea = [
      'https://yesno.wtf/',
  ];

  var randomIndex = Math.floor(Math.random() * contentArea.length);
  var randomMessage = contentArea[randomIndex];
  
  const message = await fetch(randomMessage).then(r => r.text())

  var messageElement = document.getElementById("contentArea");
  messageElement.innerHTML = message;
}

window.onload = displayRandomMessage
<div id="contentArea"></div>