Halhelms
SIGN UP FOR MY NEWSLETTER
 
 
Halhelms

Shameless Money

Recent Comments

Recent Entries

RSS

Subscribe

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:

$(document).ready(function(){
$('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);
})
});
Now, what was a chore becomes really easy. I love jQuery.

Note: This works with HTML pages, but ColdFusion pages will still interpret the code.

Comments
Lamar Brantley's Gravatar Now, that is slick. Nice.
# Posted By Lamar Brantley | 12/12/08 6:27 PM
Mikey's Gravatar Hi, I'm having trouble getting this to work. I mean, the CF tags in the textarea still seem to get processed. Hmm, any chance of an example?

Many thanks. jQuery rocks!
# Posted By Mikey | 12/12/08 10:32 PM
Hal Helms's Gravatar Mikey: I was referring to HTML pages. Sorry, I didn't make that clear. I'll fix the post.
# Posted By Hal Helms | 12/12/08 11:12 PM
 
   
Clicky Web Analytics