1

I am trying to format JavaScript code snippet to display on a web page as follow:-

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

I got the clue from this SO Link.

I have included all the files and followed the instrucntion but its not formatting it rather showing the snippet as combined.

Here is a screen shot enter image description here

I am getting the code from json file that is why it is in a single line.

I have removed the <script> and the result is same.

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

Any clue how may I intend it properly ?

Afnan Ahmad
  • 2,492
  • 4
  • 24
  • 44
  • 2
    1: this is real script, so it _will run_, it is not inert text. 2: did you remember to set the CSS for `script { display: block; }` or something? Because script elements are not shown by default, for obvious reasons. – Mike 'Pomax' Kamermans Jan 01 '19 at 16:53
  • @ MikePomax I have removed the script tag still its the same. – Afnan Ahmad Jan 01 '19 at 16:55

1 Answers1

0

If you wish to show the indents, you need to format the content in a multi-line string.

document.getElementById('src').textContent = 
`
$(document).ready(function(){ 
   setTimeout(function(){ 
      console.log('deleting cookie'); 
      $.cookie('cookie',null,{domain: document.domain}); 
   },1000); });
`;
<pre class="prettyprint">
     <code class="javascript" id="src"></code>
</pre>

BTW, please do not use document.getElementById('src').innerHTML = xxx, since <script> inside the string would be valid javascript code and would be executed

Tang Yun
  • 159
  • 9
  • I am reading it from json file and cannot do it in a multi line. – Afnan Ahmad Jan 01 '19 at 17:04
  • I don't think the google's code prettify supports auto-indent or auto-format the code, which is going to be too heavy, since there are too many programming languages to cover... – Tang Yun Jan 01 '19 at 17:18