--- title: コード例 slug: MDN/Structures/Code_examples tags: - Code - Landing - Live - MDN Meta - Static - Structures - インタラクティブ - 例 translation_of: MDN/Structures/Code_examples ---
{{MDNSidebar}}
{{IncludeSubnav("/ja/docs/MDN")}}

MDN には、Web プラットフォーム機能の使用方法を示すために、多数のコード例がページ全体に挿入されています。この記事では、コード例をページに追加する際に使用できるさまざまなメカニズムと、使用する必要があるものとそのタイミングについて説明します。

どのような種類のコード例が利用できますか?

There are four types of code example available on MDN:

We'll discuss each one in later sections.

いつそれらを使うべきですか?

Each type of code example has it own use cases. When should you use each one?

If you are not sure which one to use, you should default to traditional or GitHub live samples, depending on which one you are most comfortable with. You are also welcome to ask for advice on our Discourse forum.

一般的なガイドライン

Aside from the specific system for presenting the live samples, as summarized above, there are style and content cconsiderations to keep in mind when adding or updating samples on MDN?

静的サンプル

By static examples, we are talking about static code blocks that show how a feature might be used in code. These are put on a page using the PRE and Syntax Highlighter buttons on the MDN editor UI. An example result might look like this:

// This is a JS example
var test = "Hello";
console.log(test);

Note: For more details on adding code blocks to MDN pages, see our Syntax highlighting article.

Optionally, you might want to show a static image of the code's resulting output. For example:

Note: For more details on adding images to MDN pages, see our Images article.

従来のライブサンプル

Traditional live samples are inserted into the page using the EmbedLiveSample macro. An \{{EmbedLiveSample}} call dynamically grabs the code blocks in the same document section as itself and puts them into a document, which it then inserts into the page inside an {{htmlelement("iframe")}}. This is most easily demonstrated with an example, so let's look at one in this section and the next.

  1. The easiest way is to press the Insert Code Sample Template button, which asks us for a title. For the example in the "{{anch("test")}}" section below, we entered "test" for the title, and the button generated the entire section for us.
  2. Next, we entered some very simple sample code into the HTML, CSS, and JavaScript code blocks.
  3. Finally, we published the page; the \{{EmbedLiveSample('test')}} call you can see in the edit view was replaced with an <iframe> containing the code running live.

If you look at the source inside the <iframe>, you'll see this:

<!DOCTYPE html>
<html>
  <head>
    <link href="https://developer.mozilla.org/static/build/styles/samples.css"
          rel="stylesheet" type="text/css">

    <style type="text/css">
      h1 {
        color: blue;
      }
    </style>
  </head>
  <body>
    <h1>Your example?</h1>


    <script type="text/javascript">
      document.querySelector('h1').onclick = function() {
        document.querySelector('h1').textContent = 'Your example?';
      };
    </script>

  </body>
</html>

その他のマクロパラメータ

The call we've used in the below example only uses one parameter — \{{EmbedLiveSample('test')}}. This simply defines which section of the document the code blocks should be grabbed from — test is the ID defined on the heading "test" below, so the macro will will grab all the code blocks inside that heading. Put another way, it will grab all the blocks below that heading, up until another {{htmlelement("h2")}} is encountered.

There are some other optional parameters available too. You can include a second and third parameter, which will be a set width and height for the <iframe>. For example \{{EmbedLiveSample('test', '100%', '100px')}}. You can use pixel values or percentage values. Reasonable defaults are used if you omit these.

There are also optional fourth and fifth parameters available, a screenshot URL that points to a screenshot showing the example should look like, and a page slug that points to another page on MDN —this is only used if you want to embed an example from another page. You won't use these two very often.

See EmbedLiveSample macro for more details on all these parameters.

伝統的なライブサンプルを使用するためのヒント

Note: You can find a lot more information about traditional Live samples in our Live samples article.

テスト

HTML

<h1>My example?</h1>

CSS

h1 {
  color: blue;
}

JavaScript

document.querySelector('h1').onclick = function() {
  document.querySelector('h1').textContent = 'Your example?';
};

結果

{{EmbedLiveSample('test')}}

GitHub ライブサンプル

GitHub live samples are inserted into the page using the EmbedGHLiveSample macro. An \{{EmbedGHLiveSample}} call dynamically grabs the document at a specified URL (which has to be inside the mdn GitHub organization), and inserts into the page inside an {{htmlelement("iframe")}}.

These work in a very similar way to the {{anch("Traditional live samples")}}, but they are a lot simpler:

You don't have to worry about placement of code blocks on the page — it simply grabs an HTML document in a GitHub repo, and puts it in the <iframe>.

The macro only has three parameters:

  1. The URL of the document to embed — this is relative to the mdn organization, the top level directory of which is at https://mdn.github.io/. So this parameter needs to contain the part of the URL after that, e.g. my-subdirectory/example.html. You can omit the filename if it is called index.html.
  2. The width of the <iframe>, which can be expressed as a percentage or in pixels.
  3. The height of the <iframe>, which can be expressed as a percentage or in pixels.

Let's look at an example. Say we wanted to embed the code at https://mdn.github.io/learning-area/css/styling-boxes/backgrounds/. We could use the following call:

\{{EmbedGHLiveSample("learning-area/css/styling-boxes/backgrounds/", '100%', 100)}}

This looks like so when rendered:

{{EmbedGHLiveSample("learning-area/css/styling-boxes/backgrounds/", '100%', 100)}}

GitHub ライブサンプルを使用するためのヒント

インタラクティブな例

The newest form of live example available on MDN is interactive live examples. These provide a step up from live examples, because the reader can edit the code and the live example updates on the fly. This is great for learning and experimentation.

The interactive examples are intended to be used at the top of MDN reference pages — we are aiming to provide these to improve their value to beginners and other readers who want to just grab and play with an example quickly before seeing all the details of whatever they are looking up. There are a few important limitations to note about the interactive examples:

If you want to submit an example, you can find out how at the interactive examples repo Contribution guide.

If you find a page that doesn't have an associated interactive example, you are welcome to contribute one! The MDN Discourse forum is a good place to ask for help or advice.

インタラクティブなサンプルデモ

The \{{EmbedInteractiveExample}} macro is used to embed finished examples into MDN pages. For example, the macro call \{{EmbedInteractiveExample("pages/js/array-push.html")}} displays the following code example:

{{EmbedInteractiveExample("pages/js/array-push.html")}}
 
Try adjusting the code to see what happens, and playing with the controls.