Skip to content

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

Carolyn MacLeod edited this page Oct 30, 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. If the page has only one example, use id="css_js_files" for consistency.

  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

How to test your changes locally

In order to test the post request to codepen, you will have to start any local webserver serve the example page. If you have python, you can run pythons simple http server like this:

  • In a terminal, run python -m SimpleHTTPServer in the aria-practices directory.
  • In your browser, navigate to your example: http://localhost:8000/example/index.html

Make sure that the example works in codepen! You might have to do some slight css editing to make it look good. Make sure whatever changes you make work in both the example page and in codepen.

Clone this wiki locally