Code Formatting in Blog Pages with jQuery
In my Occasional Newsletter, I want to have my code nicely formatted. And I want to just copy working code to display it. ColdFusion code has those troubling angled brackets that play havoc with browser display. I didn't want to have to swap those for the HTML entity representations. Also, when I indent my code, I use tabs instead of spaces. I didn't want to have to manually replace every tab with non-breaking spaces.
Here's what I came up with:
1. I place my code in a TEXTAREA.
2. I style the TEXTAREA via CSS to remove the borders, provide a light grey background, switch the font, and change the font color.
3. I wrote a little bit of jQuery that...
a. sets the "cols" and "rows" setting of the textarea dynamically
b. replaces all tabs with non-breaking spaces
Here's the jQuery:
$('textarea').each(function(){
$(this).val($(this).val().replace(/ /g,' '));
$(this).attr('rows',$(this).val().split("\n").length);
$(this).attr('cols',80);
$(this).attr('readonly', true);
})
});
Note: This works with HTML pages, but ColdFusion pages will still interpret the code.


Many thanks. jQuery rocks!