POST to Prefill Editors

You can start a new Pen with code and settings that you send across programatically

To pre-fill a Pen with code and options you choose, you can POST to https://codepen.io/pen/define/ with data, where the value of data is JSON containing all the bits you want pre-filled. Here is a simple example:

Note that the quotes above are escaped but the HTML isn't. You may escape or not escape code as you wish, just be careful that quotes don't screw up the HTML when you put the JSON into the value of the hidden data input. Also note that you can't make a form like the above directly from CodePen, as we don't allow form submissions in Pens (security concern).

Dynamically Create an "Edit on CodePen" Button

Let's say you had some code on a page and wanted to include a button to "Edit on CodePen". This code is different every time, so you don't want to have to update the button-making code. Here's an example of how you could do that with jQuery.

1. Find and loop through all the <pre> code blocks

$("pre").each(function() {
});

2. Figure out if the <pre> has a <code> inside or not.

It's common that they do, but they don't always. Then set up some variables we'll use later.

4. Create JSON out of the code

var data = {
html : HTML,
css : CSS,
js : JS
};

5. Escape all quotes to make sure the JSON doesn't get wonky when it is a form value

var JSONstring =
JSON.stringify(data)
// Quotes will screw up the JSON
.replace(/"/g, "&​quot;") // careful copy and pasting, I had to use a zero-width space here to get markdown to post this.
.replace(/'/g, "&apos;");