Skip to content

Instantly share code, notes, and snippets.

@dreamyguy
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreamyguy/91f10d7d52dfc3d86292 to your computer and use it in GitHub Desktop.
Save dreamyguy/91f10d7d52dfc3d86292 to your computer and use it in GitHub Desktop.
Load 1 out of N number of javascript functions randomly
<!DOCTYPE html>
<html>
<head>
<title>Random Functions</title>
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
</head>
<body>
<div id="top" style="height: 400px"></div>
<div id="bottom" style="height: 400px"></div>
<script type="text/javascript">
// a function that does something we can see...
var doit = (function() {
'use strict';
return {
// Default options. All of these can be overridden by the user
options: {
elem1: 'top',
elem2: 'bottom',
color1: 'cyan',
color2: 'magenta'
},
// Initialize the script
init: function(options) {
// Override default options with user supplied options
for (var attrname in options) {
this.options[attrname] = options[attrname];
}
// Do the thing
this.thafunction();
},
// Tha function!
thafunction: function() {
var cl1 = this.options.color1;
var cl2 = this.options.color2;
var el1 = document.getElementById(this.options.elem1);
var el2 = document.getElementById(this.options.elem2);
// jazz!
el1.style.backgroundColor = cl1;
el2.style.backgroundColor = cl2;
}
};
})();
// a function that loads another function with 2 sets of different options - randomly
function randomFunctionLoader() {
var r = Math.floor(Math.random() * 2); // number multiplied by matches the number of cases
switch (r) {
case 0:
doit.init({
elem1: 'top',
elem2: 'bottom',
color1: 'red',
color2: 'green'
});
console.log(r); // optional, just to see which option is loading when
break;
case 1:
doit.init({
elem1: 'top',
elem2: 'bottom',
color1: 'orange',
color2: 'blue'
});
console.log(r); // optional, just to see which option is loading when
break;
default: // executed when none of the values match the value of the expression (which in this case is 'r')
console.log('There is something wrong with the randomizer!'); // optional, good as a backup in other contexts
}
}
randomFunctionLoader();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment