Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display javascript as code snippet

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?

like image 532
Webster Gordon Avatar asked Jul 19 '13 18:07

Webster Gordon


People also ask

What is JavaScript code snippets?

The JavaScript snippet collection contains a wide variety of ES6 helper functions. It includes helpers for dealing with primitives, arrays and objects, as well as algorithms, DOM manipulation functions and Node. js utilities.

How do I enable code snippet?

On the menu bar, choose Edit > IntelliSense > Insert Snippet. From the right-click or context menu in the code editor, choose Snippet > Insert Snippet.

How do I display code snippets in HTML?

Using pre & code tag The text will be displayed exactly as written in the HTML source code. The <code> tag is used to define a piece of computer code. The content inside is displayed in the browser's default monospace font. So, by using <pre> & <code>, you can display a code snippet such as function.


3 Answers

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.

like image 55
Travis Avatar answered Sep 30 '22 16:09

Travis


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;
like image 35
Jim Avatar answered Sep 30 '22 15:09

Jim


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>
like image 38
basher Avatar answered Sep 30 '22 15:09

basher