views:

323

answers:

3

Hi everyone,

I need to be able to rotate content inside a placeholder div based on percentage like this. The rotation will occur on page load. So each time a user reloads a page he has these chances of seeing content 1, 2 or 3 in the content placeholder:

Content 1 = show 50% of the time
Content 2 = show 25% of the time
Content 3 = show 25% of the time

I prefer Javascript but if there is a easier way to do it in ASP.NET on the front end template not the codebehind, that is also acceptable. If you have a solution or can point me to an existing script I would appreciate it. Thanks!

A: 

Here is a quick hack, there is probably a better way.

var randomnumber=Math.floor(Math.random()*4)
if((num==0) || (num==1)) {
//show hidden div or document.write (50% probability)
} else if (num==2) {
//show hidden div or document.write (25% probability)
} else {
//show hidden div or document.write (25% probability)
}
Andrew Austin
If you use floor, values will be in range from 0 to 3, not 1 to 4
Damir Zekić
You're right, thanks.
Andrew Austin
A: 

For the random part of the script, you just have to play with Math.random Something ugly and hardcoded would look like this :

var contentToShow = -1;
var NB_MAX = 4;
var myRand = Math.floor(Math.random()*NB_MAX);
if(myRand<1) contentToShow = 1;
else if (myRand<2) contentToShow = 2;
else contentToShow = 3;

Then you just have to load the content with ajax.

An exemple in jQuery could look like :

var myPlaceHolder = $("#myPlaceHolder")
$.myPlaceHolder.load("/mycontents/mycontent_" + contentToShow + ".asp");

But using ajax request on a page load is not the way to go imo. ( 2 server request instead of 1 if the random content is handled by the server )

Spark
This is the correct implementation, but I would agree that it needs to be handled server side to get better results. (Bringing in Ajax content on load will probably look awkward)
Jeff Davis
+3  A: 

There's really no need to multiply/floor/ceil anything: the Math.random() function gives value which is larger than or equal to 0 and less than 1.

The following code would be a bit easier to maintain if you change the number of options or the chance percentage.

var contentId, random = Math.random();

if (random < 0.5) {
  // option 1: chance 0.0–0.499...
  contentId = 0;
} else (random < 0.75) {
  // option 2: chance 0.50—0.7499...
  contentId = 1;
} else {
  // option 3: chance 0.75–0.99...
  contentId = 2;
}

loadContent(contentId);
Damir Zekić
Thanks Damir, I ended up using this one and it works exactly how I wanted it to work. Plus it saves a few lines of code.
Dan