Javascript content rotation based on percentage

frontend, javascript, rotation

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);

Problem

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!

Original source