March 18, 2024 - Randomizing Code (JS)
Here's my favorite code to display a random message or picture on your website each time the page is reloaded. I don't actually know Javascript (or anything other than HTML) but I stole this code off of google and fell in love with it:
<script language="javascript">
var arrayName = new Array ();
arrayName[0] = "put one set words, pictures or code you want as an option here";
arrayName[1] = "put another set words, pictures or code you want as an option here";
arrayName.sort(() => Math.random() - 0.5);
document.write("<p>Your randome thing is: </p>" + arrayName[0] + "<p>!</p>");
</script>
This code creates an array (list of things) and mixes it up so that when you tell the script to write a certain entry in the array it gives you a random thing out of the array. I also have code on my website that gives me one random thing out of a set, but I prefer this code because it can be used to create many random selections that don't repeat.
Tips:
- AThe stuff you put in the array and document.write quotation marks is going to come out as html code
- With any code you're putting in "" in javascript change the " to '
- The "" + arrayName[0] can go on forever and you can use another number later to select another random thing different than the first
- You can change the array name to whatever you want for organization
Example