if (Math.random() > 0.5)

Hello,

I have this small script that change on refresh. I want to make sure that it displays 50 / 50% to the visitors.

is if (Math.random() > 0.5) than correctly chosen?
is there a better way to do this?
<html > 
<head> 
<title>Random Images</title> 
<script type="text/javascript"> 
//<![CDATA[ 
var images1="image_1.jpg"; 
var imglink1="http://www.test1.com";
var alt1="test1";
 
var images2="image_2.jpg"; 
var imglink2="http://www.test2.com";
var alt2="test2";
 
function randomImage() { 
if (Math.random() > 0.5) {
document.getElementById("random").src=images1; 
document.getElementById("link").href=imglink1; 
document.getElementById("random").alt=alt1; 
}
else {
document.getElementById("random").src=images2; 
document.getElementById("link").href=imglink2; 
document.getElementById("random").alt=alt2; 
}
} 
onload=randomImage; 
//]]> 
</script> 
</head> 
<body > 
<div id="container"> 
<a href="" id="link"><img id="random" src="" alt=""/></a> 
</div> 
</body> 
</html>

Open in new window

mvanthofAsked:
Who is Participating?
 
Michel PlungjanConnect With a Mentor IT ExpertCommented:
However I would do this instead:

<html > 
<head> 
<title>Random Images</title> 
<script type="text/javascript"> 
//<![CDATA[
function crtImage(imgUrl,href,title) {
  this.imgUrl = imgUrl;
  this.href=href;
  this.title=title
} 
var myImages = new Array(
  new crtImage("image_1.jpg","http://www.test1.com","test1"),
  new crtImage("image_2.jpg","http://www.test2.com","test2")
); // note the lack of comma on the last item  
 
function randomImage() { 
  var rnd = parseInt(Math.random()*myImages.length);
  var imgObj = myImages[rnd];
  document.getElementById("random").src=imgObj.imgUrl; 
  document.getElementById("link").href=imgObj.href; 
  document.getElementById("link").title=imgObj.title; 
} 
window.onload=randomImage; 
//]]> 
</script> 
</head> 
<body > 
<div id="container"> 
<a href="" id="link"><img id="random" src="" alt=""/></a> 
</div> 
</body> 
</html>

Open in new window

0
 
David S.Commented:
I'd use ">=" instead of just ">" because the range is between 0 (inclusive) and 1 (exclusive).

No, there is no better way to do it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.