jquery logo

Geshi code to plain text JQuery javascript toggle

I was about to update my somewhat limited Geshi helper to handle more code types and to sort out the added character errors when pasting a copied code block when I stumbled upon Mark Story's Geshi Helper and took a look.

Marks code was super simple to install and setup, the only problem I struck was the HTML code type in the latest Geshi version 1.0.8.1 wasn't defined so I just copied html4strict.php to html.php and it was away laughing. Mark has made it very easy to extend the code types and has even put together some nice style sheets.

The next thing to sort out on my list was the extra character errors being output when pasting a code block, I noticed in the Geshi docs that there is a new option GESHI_HEADER_PRE_TABLE, well new to me since I last looked anyway. I gave that a crack first but found it still lost formatting when pasting a code block. Mark has also provided a MooTools javascript example but since I had just started using JQuery I converted the code as best I could. It took a little bit of hacking around as IE wouldn't play nice (like normal), anyway here's what I came up with for my JQuery code if anyones interested :-

Show Plain Text
Javascript code
  1. <script type="text/javascript">
  2. jQuery(document).ready(function() {
  3.   jQuery(".code").each(function() {
  4.     var block = jQuery(this);
  5.     var htmlText = block.html();
  6.     var plainText = "";
  7.     if (jQuery.browser.msie) {
  8.       plainText = htmlText.replace(/\n/g, "+");
  9.       plainText = jQuery(plainText).text().replace(/\+\+/g, "\r");
  10.     } else {
  11.       plainText = block.text().replace(/code/g, "code\n");
  12.     }
  13.     var state = 1;
  14.     block.prev().click(function() {
  15.       if (state) {
  16.         jQuery(this).html("Show Highlighted Code");
  17.         block.text(plainText).wrapInner("<pre class=\"plain-text\"></pre>");
  18.         state = 0;
  19.       } else {
  20.         jQuery(this).html("Show Plain Text");
  21.         block.html(htmlText);
  22.         state = 1;
  23.       }
  24.     });
  25.   });
  26. });
  27. </script>

I have tested the code under IE6, IE7, and FF3 so far.

Filed under: Cakephp, Javascript  Tags: Jquery

1 Responses to “Geshi code to plain text JQuery javascript toggle”

nice - I hope to retain this for near future use

Sorry, comments have been closed for this post.