Categories
Words

MadLib Writer’s Prompt

Let’s write some Javascript to generate a writer’s prompt from a list of nouns, verbs, adjectives, and adverbs, etc.

First, we’ll add some loading code. This code gets invoked two ways: first, we run it when the window is finished loading, so we get can update the DOM and give the user something to look at. We’ll also add a button to generate a new MadLib on demand.

window.onload = generate_prompt();

This is our workhorse right here, but it’s pretty simple. We have a bunch of arrays and we’re going to pick from them a random element and add it to the string.

function generate_prompt() {
	
     prompt_string = adjective1[random_0_to(adjective1.length)] + " " + 
          media[random_0_to(media.length)] + " " + 
          adjective2[random_0_to(adjective2.length)] + " " + 
          noun[random_0_to(noun.length)] + " " +
          action[random_0_to(action.length)] + " " +
          venue[random_0_to(venue.length)] + " ";
	
	if (random_0_to(10) == 0)
		prompt_string += ", in Latin."
		else  
		prompt_string += "."

	display_prompt(prompt_string);		
	}

Here are some sample arrays to get you going. You can add as many elements as you’d like to the arrays, just make sure they’re all separated by a comma.

var prompt_string = ""

var adjective1 = [
	"A gripping",
	"a frivolous"
]

var media = [
	"novel starring",
	"short story about"
]

var adjective2 = [
	"an anxious",
	"a pretentious"
]
var noun = [
	"duck",
	"bunny"
]

var action = [
	"dancing",
	"flying"
]

var venue = [
	"on the moon",
	"in my imagination"
]

We’re going to need a function to generate those random numbers.

function random_0_to(n) {
	return Math.floor(Math.random() * n);
	}

And lastly, a function to update the DOM.

function display_prompt(s) {
	document.getElementById("prompt").innerHTML = s;
	}

Cool, all done with the .js file.

This is from the HTML file that I use here at www.floatingpoint.pub. It defines the area in the DOM where the prompt gets updated by the display_prompt(s) function and contains a little self-contained javascript to update the prompt when someone clicks the (new) link.

		<p class=prompt><strong>PROMPT:</strong>
		<a id="prompt"></a>
		<a href="javascript:generate_prompt()" style="text-decoration:none !important;">(new)</a>
		</p>

That’s it! Have fun with it and be sure to email me to show off how you’ve used it to do something really cool on your own.