Skip to content

Instantly share code, notes, and snippets.

@Mikescops
Last active October 11, 2017 22:03
Show Gist options
  • Save Mikescops/e26a78da0d7d3563c1be to your computer and use it in GitHub Desktop.
Save Mikescops/e26a78da0d7d3563c1be to your computer and use it in GitHub Desktop.
Generate a random number into html with jQuery process.
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<p><a href="no-javascript.html" id="getNumber">Générer</a> un nombre aléatoire. </p>
<h2 id="result"></h2>
<script>
var link = document.getElementById('getNumber');
link.onclick = getNumber;
function getNumber() {
var minNumber = 1; // le minimum
var maxNumber = 100; // le maximum
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // la fonction magique
$('#result').html(randomnumber);
return false;
}
</script>
</body>
@sohils
Copy link

sohils commented Apr 15, 2017

If you change the maximum and minimum limits, your function will return an incorrect value.
Changing this line from:
var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber);
to this:
var randomnumber = Math.floor(Math.random() * (maxNumber - minNumber + 1) + minNumber);
works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment