Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the JS codes inside pre or code block executes?

I have been trying to show some JS codes in a page.I have tried using

<pre >
    <code>
        <script type="text/javascript"> 
            $(function(){
                alert("Hello");
            });
        </script>
    </code>
</pre>

But if jQuery is loaded in the page then the I am getting an alert and the code is not being shown. How can i show this JS without executing the JS. I tried SyntaxHighLighter plugin and it's highlighting the code but still i am getting the alert.

What is the best way to show this JS code to users without executing them.

like image 852
Prasenjit Kumar Nag Avatar asked May 24 '11 09:05

Prasenjit Kumar Nag


People also ask

What is code block in JS?

A block statement is used to group zero or more statements. The block is delimited by a pair of braces ("curly brackets") and contains a list of zero or more statements and declarations.

Why my JavaScript is not working?

On the web browser menu click on the "Edit" and select "Preferences". In the "Preferences" window select the "Security" tab. In the "Security" tab section "Web content" mark the "Enable JavaScript" checkbox. Click on the "Reload the current page" button of the web browser to refresh the page.

How do I see what JavaScript is doing?

View web page source code For most browsers, to view inline JavaScript in the HTML source code, do one of the following. Press the Ctrl + U keyboard shortcut. Right-click an empty area on the web page and select the View page source or similar option in the pop-up menu.


2 Answers

Because neither <pre> nor <code> mean "Don't treat this as markup".

<pre> means "Render whitespace here"

<code> means "Present this (i.e. use an appropriate font, etc) in such a way that it informs the reader that it is a code sample".

If you want to use characters which have special meaning in HTML (such as <) then you still have to use entities to represent them.

  • &lt; for <
  • &gt; for >
  • &amp; for &

You don't need to worry about ' or " as you aren't inside an attribute value.

like image 53
Quentin Avatar answered Sep 28 '22 11:09

Quentin


Using <script> tags means that this is javascript to be executed.

Remove the <script> tags altogether:

<pre>
<code>
$(function(){
        alert("Hello");
    });
</code>
</pre>

Alternatively, encode the < and > to &lt; and &gt; so the <script> tags are rendered as text and not interpreted as script tags:

<pre>
<code>
&lt;script type="text/javascript"&gt;
$(function(){
        alert("Hello");
    });
&lt;/script&gt;
</code>
</pre>
like image 27
Oded Avatar answered Sep 28 '22 11:09

Oded