Using jQuery to execute sample code displayed in XHTML

Here we have a JavaScript snippet in <pre/> tags with a class of “execute” and additional markup.

alert("There are " + $("a").size() + " links on this page");

Then as a master controller, you’d have something like this which will execute all the sample code in your page–

<script type="text/javascript">//<![CDATA[
$(function() {
  $("pre.execute").each(function(){
    eval( $(this).text() );
  });
});
//]]> </script>

To see it in action, click here.

This has two major benefits–

  1. The code that is executed is the code that is displayed. If it runs, it’s right. There is no chance for drift between the real code and the sample if you tweak one and forget to update the other because the sample is the real code.
  2. As you can see above, you can include markup with your samples so you can do things like highlight updated code.

Thanks to the excellent Mike Alsup for revealing this technique in his site.

digg stumbleupon del.icio.us reddit Fark Technorati Faves
Your information (required) Name*
Email*
Website

* Indicates required fields; email is used for validation and is not displayed on the site.

Your comment
Commenting on Using jQuery to execute sample code displayed in XHTML
Title

Body is limited to ≈1,000 words. Paragraphs—but not line breaks—are automatically inserted. Valid XHTML is required. These are the allowed tags–

<a href=""></a> <br/> <acronym title=""></acronym> <abbr title=""></abbr> <code></code> <pre></pre> <tt></tt> <ins></ins> <del></del> <hr/> <cite></cite> <b></b> <i></i> <sup></sup> <sub></sub> <strong></strong> <em></em> <h1></h1> <h2></h2> <h3></h3> <q></q> <blockquote></blockquote>