Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-apply prettyPrint AFTER run_prettify.js has been loaded

I'm trying with Javascript code prettifier, and come up with a question.

If I do not assign class="prettyprint" to <pre> in static html, but wish to apply prettyprint later(e.g, when user click on a "colorize" button on my webpage), how can I achieve this?

Slightly modifying original run_prettify.js or prettify.js is acceptable, because I'm going to put this to offline use.

My experiment:

Writing try-delay-class.html:

<html>
<head>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
</head>
See it:
<pre>
class Voila {
public:
  // Voila
  static const string VOILA = "Voila";

  // will not interfere with embedded <a href="#voila1">tags</a>.
}
</pre>
</html>

Open in Chrome v26, bring up the console, execute:

pres=document.getElementsByTagName('pre')
pres[0].className+=" prettyprint"

Syntax color does not come up.

enter image description here

like image 444
Jimm Chen Avatar asked Apr 21 '13 01:04

Jimm Chen


2 Answers

According to a comment found here, How to get prettyprint to work on dynamically generated dom element , I find the way out. Just call:

PR.prettyPrint()

BTW: If you want to remove code color highlight, you cannot simply set pre's class to empty followed by PR.prettyPrint() again. PR.prettyPrint() can only attach color tags but not remove them. A feasible way to do that is saving your original <pre> content before applying prettyprint, then restore <pre>s content later. Verified in my post jQuery, how to clone back saved elements? .

enter image description here

like image 170
Jimm Chen Avatar answered Oct 06 '22 01:10

Jimm Chen


You can find three examples here

I did it as follows in js:

document.getElementById('outputa').innerHTML = 
 PR.prettyPrintOne("your code in brackets or your variable (without these brackets)",
 'java');
like image 36
Ula Avatar answered Oct 06 '22 00:10

Ula