Display javascript as code snippet
Asked Answered
S

5

8

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?

Smokechaser answered 19/7, 2013 at 18:38 Comment(1)
Try viewing the source HTML of this question, that'd show you one way.Interlay
C
14

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.

Codpiece answered 19/7, 2013 at 18:42 Comment(0)
L
5

The problem you have is that you are entering HTML and you want it to not be treated as HTML. Specifically, the opening <script> element.

In order to enter HTML that will not be parsed as HTML, you need to encode characters that are special to HTML. For instance < is encoded as &lt;, > is encoded as &gt;, and & is encoded as &amp;.

So, to output the following without it being parsed as HTML:

<script>...</script>

...you need to enter:

&lt;script&gt;...&lt;/script&gt;
Lisandralisbeth answered 19/7, 2013 at 18:42 Comment(0)
R
2

It's running because of the <script> tags. You should encode them:

<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>
Resonance answered 19/7, 2013 at 18:42 Comment(0)
I
0

use &lt;script&gt; and &lt;/script&gt; for <script> tag

Inattentive answered 19/7, 2013 at 18:42 Comment(0)
P
-1

Let the textContent property (or createTextNode) do all the heavy lifting of encoding whatever text you need to insert into dom:

var sampleCode="<script> $(document).ready(function(){ setTimeout(function(){ console.log('deleting cookie'); $.cookie('cookie',null,{domain: document.domain}); },1000); }); </script>";
var pre=document.createElement("pre");
pre.textContent=sampleCode;
pre.className="prettyprint";
document.body.appendChild(pre);
Pagurian answered 19/7, 2013 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.