Skip to content

How to add the Open In Codepen button to an example page

Matt King edited this page Jul 7, 2020 · 4 revisions

This page explains how to add an "Open in Codepen" button to an existing example page. If you are creating a new example, you will get this all for free by starting from the example template.

The way the button works:

In all example pages, we import the helper js/examples.js and run the sourceCode.add and sourceCode.make with the appropriate arguments. These functions do the following two things:

  1. Pull the html of the example from the example page and prints it prettily under the HTML Source Code header.
  2. Fetch the css and js files listed under the Javascript and CSS Source Code header and creates a post request to prefill a CodePen page with the html, css and javascript from the example.

Some example pages have more than one example or specific language, so the information passed to sourceCode.add specifies where in the page to find the example html, the javascript and css file links and where to put the "Open in Codepen" button.

The js/example.js API is documented in the source code.

Steps to add the button to existing examples:

  1. To get appropriate styling on the button, wrap the example header in a div with class example-header:

    • If the page has only one example, wrap the h2 header with text "Example" in a div with class example-header
    • If the page has more than one example, wrap the h3 that head the beginning of each separate example widget in a div with class example-header.
  2. Add an id to an element that contains a list of links to all the relevant JS and CSS files for each example. This is usually a ul element under the Javascript and CSS Source Code section.

  3. For each example, there should be a script tag with a sourceCode.add function call with two positional arguments. Add a third and fourth positional argument:

    • Third argument: ID of header element under which the "Open in Codepen" button belongs (usually h2 or h3 with the word 'Example').
    • Fourth argument: ID of element you added in step two
Clone this wiki locally