Display javascript as code snippet

Webster Gordon picture Webster Gordon · Jul 19, 2013 · Viewed 15.8k times · Source

What I'm trying to do is display a snippet of javascript on the page, and not have it run, just display as a code snippet for folks to copy. I load google's Prettify, then in the page I have this code:

    <pre class="prettyprint">
    <script>
    $(document).ready(function(){
      setTimeout(function(){
        console.log('deleting cookie');
        $.cookie('cookie',null,{domain: document.domain});
     },1000);
    });
    </script>
   </pre>

But this code just executes and doesn't display the JS snippet. What am I missing here?

Answer

Travis picture Travis · Jul 19, 2013

You need to convert your < and > characters to HTML entities like so:

<pre class="prettyprint">
  &lt;script&gt;
    $(document).ready(function(){
      setTimeout(function(){
        console.log('deleting cookie');
        $.cookie('cookie',null,{domain: document.domain});
      },1000);
    });
  &lt;/script&gt;
</pre>

I would also recommend wrapping the code in <code> tags in addition to the existing <pre> tags.