0

I'm helping my friend build a website, I am trying to set it up so the homepage randomly redirects through to one of the pages, setup for three now, but with the ability to add more.

At the moment it seems to work some of the time, but doesn't go through sometimes, and it seems to redirect to one of the rooms way more than others?

<script type="text/javascript">

//RANDOMLY REDIRECTS TO A ROOM !

var doors = Math.floor(Math.random() * 3) + 1;

    if (doors == 1) {
      window.location.href = 
"http://sarahboulton.co.uk/kitchen.html";
      }

    else if (doors == 2) {
      window.location.href = 
"http://sarahboulton.co.uk/livingroom.html";
      }

    else if (doors == 3) {
      window.location.href = 
"http://sarahboulton.co.uk/chapelbedroom.html";
      }

</script>
CodeF0x
  • 2,624
  • 6
  • 17
  • 28
joehigh1
  • 193
  • 12
  • 1
    `"it seems to redirect to one of the rooms way more than others?"`, maybe just probability,no? – Ferus7 Nov 19 '18 at 14:28
  • 1
    Random is not uniform, nor is it predictable. – jhc Nov 19 '18 at 14:30
  • Your posibilities range from 1 to 3, there's not very much variation possible: http://jsfiddle.net/h89526ek/. You may also want to read this: https://stackoverflow.com/questions/2344312/how-is-randomness-achieved-with-math-random-in-javascript – CodeF0x Nov 19 '18 at 14:33

2 Answers2

0

You can do it like that. You just have to put your new entries in the Array.

var rooms = ["http://sarahboulton.co.uk/kitchen.html", 
    "http://sarahboulton.co.uk/livingroom.html", 
    "http://sarahboulton.co.uk/chapelbedroom.html"];

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

window.location.href = getRandomInt(0, rooms.length-1);
BadRequest
  • 382
  • 1
  • 14
0

Create an array with the file names. choose a random number which should be the index for the array. Here is the code

<script type="text/javascript">

//RANDOMLY REDIRECTS TO A ROOM !


var pages = [ 'Kitchen', 'livingroom', 'chapelbedroom' ];

var doors = Math.floor(Math.random() * ( pages.length - 1 ));

var url = 'http://sarahboulton.co.uk/' + pages[doors] + '.html';

window.location = url;



</script>