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