Javascript content rotation based on percentage
-
06-07-2019 - |
Question
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!
Solution
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);
OTHER TIPS
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 )
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)
}