--- title: Live samples slug: MDN/Structures/Live_samples tags: - Guide - Intermediate - MDN Meta - NeedsTranslation - Structures - TopicStub translation_of: MDN/Structures/Live_samples ---
MDN supports turning sample code displayed in articles into running samples the reader can look at in action. These live samples can include HTML, CSS, and JavaScript in any combination. Note that "live" samples are not interactive; however, they do ensure that the output displayed for a sample matches the code of the sample exactly, because it is actually generated by the code sample.
The live sample system gathers up all the code in a group, merges it into one HTML file, and then renders that HTML in an {{HTMLElement("iframe")}}. A live sample therefore consists of two pieces:
A "group" of code blocks, in this context, is identified by the ID of a heading or a block element (such as a {{HTMLElement("div")}}).
The macro uses a special URL to fetch the sample code for a given group: http://url-of-page$samples/group-id
, where group-id
is the ID of the heading or block where the code is located. The resulting frame (or page) is sandboxed, secure, and technically may do anything that works on the Web. Of course, as a practical matter, the code must contribute to the point of the page that contains it; random stuff running on MDN will be removed by the editor community.
Note: You must use the macro for presenting the live sample's output. MDN's editor will strip out any direct use of the <iframe>
element in order to ensure security.
Each {{HTMLElement("pre")}} block containing code for the sample has a class on it that indicates whether it's HTML, CSS, or JavaScript code; these are "brush: html", "brush: css", and "brush: js". These classes must be on the corresponding blocks of code so that the wiki can use them correctly; fortunately, these are added for you automatically when you use the syntax highlighter features in the editor's toolbar.
The live sample system has lots of options available, and we'll try to break things down to look at them a bit at a time.
There are two macros that you can use to display live samples:
EmbedLiveSample
embeds a live sample into a pageLiveSampleLink
creates a link that opens the live sample in a new pageIn many cases, you may be able to add the EmbedLiveSample
or LiveSampleLink
macro to pages with little or no additional work! As long as the sample can be identified by a heading's ID or is in a block with an ID you can use, simply adding the macro should do the job.
\{{EmbedLiveSample(block_ID, width, height, screenshot_URL, page_slug)}}
px
. This is optional; a reasonable default width will be used if you omit this. Note that if you want to use a specific width, you must also specify the height parameter.px
. This is optional; a reasonable default height will be used if you omit this. Note that if you want to use a specific height, you must also specify the width parameter. If you use only one of them, the default frame size is used.\{{LiveSampleLink(block_ID, link_text)}}
The sections below describe a few common use cases for the live sample system.
In all of these cases, to see the results of the live sample, you must click Save Changes in the editor (which takes you out of edit mode). Because of the reflexive, Inception-like nature of live samples, the Preview Changes functionality is not able to display live samples.
One common use case is to take existing code snippets already shown on MDN and turn them into live samples.
The first step is to either add code snippets or ensure that existing ones are ready to be used as live samples, in terms of the content and in terms of their mark-up. The code snippets, taken together, must comprise a complete, runnable example. For example, if the existing snippet shows only CSS, you might need to add a snippet of HTML for the CSS to operate on.
Each piece of code must be in a {{HTMLElement("pre")}} block, with a separate block for each language, properly marked as to which language it is. Most of the time, this has already been done, but it's always worth double-checking to be sure each piece of code is configured with the correct syntax. Next to the PRE icon in the toolbar is a drop-down menu icon (tooltip: Syntax Highlighter) with the various languages that MDN does syntax highlighting for. Setting the language for the block for syntax highlighting also correlates it with a language for the purposes of the live sample system.
Note: You may have more than one block for each language; they are all concatenated together. This lets you have a chunk of code, followed by an explanation of how it works, then another chunk, and so forth. This makes it even easier to produce tutorials and the like that utilize live samples interspersed with explanatory text.
So make sure the {{HTMLElement("pre")}} blocks for your HTML, CSS, and/or JavaScript code are each configured correctly for that language's syntax highlighting, and you're good to go.
Note: When pasting content into MDN, please be aware that if pasting styled content (including, for example, syntax highlighting in code being copied from another site) that you may be bringing along unwanted and unneeded additional styles or classes. Please be careful not to do this; if necessary, review your edit in source mode to remove these unnecessary styles and classes (or check it before pasting, or use the "Paste as plain text" option instead).
Once the code is in place and properly configured to identify each block's language, you need to insert the macro that creates the iframe.
If you're writing a new page, and want to insert code that you want to present as a live sample, even more of the work can be done for you by the editor!
As mentioned above, the Sample Finder is activated by clicking the Insert Live Code Sample iFrame icon. Unfortunately the Sample Finder may produce a macro that is NOT usable without editing. There are two problem areas that should be carefully checked and edited if necessary.
Here is what the Sample Finder produced:
\{{ EmbedLiveSample('Examples', '', '', '', 'Web/CSS/@counter-style') }}
This macro will not work. The block_ID is Examples and it should be Example in this case (check the source ID for this section to verify which block_ID you need to use. Similarly the page_slug is @counter-style and it should be @counter-style/negative. These corrections can be done directly in the page with Edit active.
After editing the macro now looks like this:
\{{ EmbedLiveSample('Example', '', '', '', 'Web/CSS/@counter-style/negative') }}
This edited macro will work correctly. If the macro is working correctly you will see the Open in CodePen button. A thumbnail of the example should appear above the Open in CodePen button. If the button is there but there isn't a thumbnail, just wait a few minutes. It may take some time for the server to generate it.
When looking for existing samples to update, there are three main kinds of updating you may wish to do:
Note: If you find an article that has samples in need of being updated to use the live sample system, please add the tag "NeedsLiveSample" to the page.
MDN has lots of older examples that don't yet use the live sample system. Our goal is to update most or all of these to be live samples. This will improve consistency and usability. You will almost certainly find many of these as you use MDN on a daily basis; however, how can you find them if you're specifically looking for them to update? Unfortunately, there's not an easy way to do that. But there are some guidelines you can follow to help track them down:
This section is the result of using the live sample template button to create not only the main heading ("Live sample demo"), but also subheadings for our HTML, CSS, and JavaScript content. You're not limited to one block of each; in addition, they don't even need to be in any particular order. Mix and match!
You may choose to delete any of these you wish; if you don't need any script, just delete that heading and its {{HTMLElement("pre")}} block. You can also delete the heading for a code block ("HTML", "CSS", or "JavaScript"), since these are not used by the live sample macro.
Now that the template has been inserted, we can put in some code, and even some explanatory text.
This HTML creates a paragraph and some blocks to help us position and style a message.
<p>A simple example of the live sample system in action.</p> <div class="box"> <div id="item">Hello world! Welcome to MDN</div> </div>
The CSS code styles the box as well as the text inside it.
.box { width: 200px; border-radius: 6px; padding: 20px; background-color: #ffaabb; } #item { font-weight: bold; text-align: center; font-family: sans-serif; font-size: 1.5em; }
This code is very simple. All it does is attach an event handler to the "Hello world!" text that makes an alert appear when it is clicked.
var el = document.getElementById('item'); el.onclick = function() { alert('Owww, stop poking me!'); }
Here is the result of running the code blocks above via \{{EmbedLiveSample('Live_sample_demo')}}
:
{{EmbedLiveSample('Live_sample_demo')}}
Here is a link that results from calling these code blocks via \{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}
:
{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}
EmbedLiveSample
macro (see above). This way, the semantic of the example is made clearer for both the reader and any tools that would parse the page (e.g. screen reader, web crawler).