0

I have this code, it should generate a random date every button pressed and update the text. however every time i press the button nothing happens(after the first press of course).

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display what day it is today.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction()
{
var x;
var d=new Date().getDay();
switch (d)
  {
  case 0:
    x="Today it's Sunday";
    break;
  case 1:
    x="Today it's Monday";
    break;
  case 2:
    x="Today it's Tuesday";
    break;
  case 3:
    x="Today it's Wednesday";
    break;
  case 4:
    x="Today it's Thursday";
    break;
  case 5:
    x="Today it's Friday";
    break;
  case 6:
    x="Today it's Saturday";
    break;
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>
Or Cyngiser
  • 1,027
  • 1
  • 12
  • 16

2 Answers2

2

You are not generating a random date. What the Date constructor does is return the current date. That's why, every time you press, the date remains unchanged.
If you want a random date, you could use this function which returns a random date between an interval :

function randomDate(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
}

and use change the line :

var d=new Date().getDay(); 

to

var d = randomDate(new Date(2012, 0, 1), new Date());

Note: the random date function is taken from : Elegant method to generate array of random dates within two dates

Community
  • 1
  • 1
gion_13
  • 41,171
  • 10
  • 96
  • 108
2

I've made a jsFiddle for you to. This absolutly works for me in terms of the current date. If you wanted to have a random number you would have to generate such a number with this code

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

where min and max are the range you want to have, i.e. 0 to 6. I've added this to the jsFiddle example.

toxicate20
  • 5,270
  • 3
  • 26
  • 38