Tips for Posting Code Online

Posted February 1st, 2009 by Mike Cherim

Many web developers who blog at some point share a little code or scripting. We do this to give away a hard-earned/hard-learned tip or trick, or in some cases to offer a whole script or code solution. We try to make the Internet a better place. This is a great thing about the web, all this openness and sharing over the years. I’ve observed over those years, though, that some post code more effectively than others. I’ve seen code posted on the web that was hard to read, difficult to access, and sometimes nearly impossible to use. Based on these observations, and based on my own personal preferences in some instances, I have come up with the following tips for posting code online.

Correctness

I guess this should come first. Whether it’s X/HTML, CSS, PHP, JavaScript, or what have you, the code posted should be of the highest quality possible. I know this isn’t always the case. Goodness knows I’ve shared code that could be improved. Still, code authors should take into consideration web accessibility, user- and server-side security, web standards, validity, and anything/anyone else that may be impacted by or applicable to the particular code or script being offered.

If the code is posted on a blog where comments are accepted, often times invaluable code tweaks and corrective advice comes from readers. Allowing an open two-way communication, improvement can happen live. Code authors should allow and encourage this. And code users should read the applicable comments left by others and chime in with their own if they have noteworthy experiences or information that might be useful to others. That’s how it works.

Pre-format It

The preformatted text element, or pre is very useful for making code readable as it preserves formatting. In other words spaces show up as spaces, indents are indents, et cetera. Bear in mind though, the code element should also be used to indicate the pre box’s contents are indeed code. I am a bit guilty on this count, I admit. I have left out the code element many times. I have no excuse, and I won’t bore you with the reason.

Other Considerations

There are many other considerations one should be make when using the pre element to post their script or code online. Here’s a short but hopefully fairly complete list:

Typeface
The typeface used should be a fixed-pitch monospace font to allow even spacing and the best code readability. A font such as “Courier New” is sound choice, but the need to declare anything isn’t necessary as monospace is the browser default anyway.
Scrollable
The pre element should be scrollable, or the browser window should scrollable. Not both, and code shouldn’t be cut off by hiding the element’s overflow. I like to set a pre element max-height of around 500px with the width determined by content area.
Copy-Ready
Some authors offer a JavaScript enhancement allowing users to “Select All.” Others drag their mouse over the code or hold Shift while arrowing down. The point is, make it copy-ready so it doesn’t have to be re-written. The next item can be of concern in regard to this.
Numbering
Some authors number their lines by way of scripts, by way of background images, and other methods. This is fine, but only if the numbers themselves can’t be copied and the page semantics aren’t destroyed in the process. Anyone have a good working example?
Indentation
Some authors indent lines of code by tabbing, and that can display enormous white space to the left of the actual code. Personally I don’t like that at all, preferring more compact indentation (using spaces only). On the web I feel all code should be compact.
Whole Strings
The beauty of a scrollable, width defined pre element is that authors can write complete strings or lines of code: No sidebar overlap, no horizontal browser scrollbar, no hidden code, and no annoying line breaks that can make the code hard to read and use.
Focusable
The pre element may be a keyboard focusable element — depending on browser and version — so style should be added to aid page navigation for applicable keyboard users. This can be accomplished by changing border color on :focus (jump to Posted Code).

Some Options

It is always possible to offer your code or script in alternative ways, instead of posting them with your content in a pre element. Some will offer code in native file formats such as offering a JavaScript example in a *.js file, or offering some CSS in a *.css file. I can’t recommend these native file methods, though, as they can be difficult to open for some users. This is another one of those depending on browser and version issues.

I think the best option, if one is take this route, is to offer the code or script in a non-threatening text (*.txt) file linked to from the main article. It’s a pretty universal file type so this approach is sound and sensible, especially where large scripts are concerned. I think that offering a large script in particular in a separate file might be considerate to screen reader users. I’m not sure, but hearing spoken code would be a bit tedious so it might be wise to err on the side of caution. Just remember that text files lack the semantic structure of HTML so don’t overly rely on them to deliver content or convey meaning to readers.

If you’re a PHP script author, you have even more options. You can create a *.phps file. That is an alternative file format offered by your server’s PHP software (may need to be enabled). The file extension creates a text-like file with all sorts of horrible HTML used to format and color the content (here’s a *.phps example). Want a laugh? View Source on that example. The PHP software server generates that. It works, though, and the color coding can be helpful to some.

Ready-to-Use

If you’re going to post code online you kind of have to figure people are going to use it. A nice person would make it not only make it Copy-Ready as I had mentioned when discussing the pre element, but they’d also make it ready-to-use. Specifically I mean authors should actually comment out all comments, make sure the actual code displayed works, and make sure strings are complete — don’t make me remove a » (») and reconstruct the line of code.

Also of importance, and this applies particularly to users of WordPress and other such authoring platforms that perform character conversions, make sure all quotes are plain quotes. Same thing with apostrophes. Sometimes the use of the code element within the pre element will correct this, but if not it needs to be done manually. In other words instead of writing "script" you’ll want to write "script", so you don’t end up with “script” and other unrecognizable characters. They will cause script errors and won’t be valid within X/HTML elements.

Posted Code

No article about posting code examples would be complete without posting a code example. Here’s something for your cascading style sheet. The image used in the background is a tiny 10×26px JPG file, repeated down and across, or on the y and x axis, respectively.

pre {
  background : #fff url(images/bb_pre.jpg) repeat;
  font : 1em 'courier new', courier, monospace;
  color : #000;
  padding : 4px;
  margin : 10px 2px;
  width : 99%;
  height : auto;
  max-height : 500px;
  overflow : auto;
  border : 2px inset #99cc66; /* light pale green */
}

pre:focus {
  border : 2px inset #cc3300; /* deep gold orange */
}

Please note: Not all of the styling shown is needed. I declared a font color to override my main style color. I also declared the font-family for the same reason. The specific attribute colors and property values used should be adjusted to meet your needs.

Your Copyright

Fuggedaboutit. If you want to prevent users from taking your code, don’t post it online. You can’t protect it once it’s there. You can ask for donations, embed a linkback, and insert a comment header, and these things should remain if you’re a code user, but you may as well give up most of your rights if you’re the author. Read my copyright to see how I deal with scripts in my blog.

For WordPress

This article is complete at this point, but I do have an extra nugget of goodness just for WordPress users. Especially those WordPress users that like to post not only styles, but also a working example of said styles… on the same page… without using in-line styles… and without having to edit their main style sheet and create yet another class.

For said users I recommend making a small edit to your theme’s header (header.php) by adding the code below — positioned after your existing style links — and then adding a “Custom Field” much like I’ve done for descriptions and keywords and custom pullquotes in past articles.

<?php if( ((get_post_meta($post->ID, pagestyles, true) != "") && (is_single())) || ((get_post_meta($post->ID, pagestyles, true) != "") && (is_page())) ) { ?>
  <style type="text/css" media="screen">
    <?php echo get_post_meta($post->ID, pagestyles, true); ?>
  </style>
<?php } ?>

For this article I applied this so you could see the output (View Source), though all I added was a comment. This article didn’t need actual styles. To make this happen, once I had inserted the code above into my theme, I performed the following:

  1. Scroll down to the “Custom Fields” section of your editor page. The location of this might vary depending on your version of WordPress. Consult your documentation.
  2. If doing this for the first time, write the word “pagestyles” in the Key input. If it’s not your first time, you can grab the “pagestyles” key from the menu.
  3. Enter your styles in the textarea just as you would in a style sheet or document head and save the custom field and its content.

This is a really easy and really convenient method, and always available, without fear of style sheet bloat or conflicts down the road. Moreover, doing this instead of using inline styles allows for the use of pseudo elements like :hover and :focus. This is good stuff. And to take it a step further, there’s no reason why this couldn’t be re-engineered to offer the same convenience for posting JavaScript or whatever you need. Maybe called it pagescripts.

If you’re a purist and want an even cleaner solution, you could change the PHP scripting above so that it outputs a link to a separate page-specific style sheet (or other) file — that would be the value — instead of the styles themselves, but for most this solution is going to meet their needs just fine. Or, you can use Joe Dolson’s new WP Post Styling plugin.


17 Responses to: “Tips for Posting Code Online”

  1. David Zemens - 1955 Design responds:
    Posted: February 1st, 2009 at 9:01 am

    As usual, Mike, good stuff! Of particular interest to me is your suggestion for WordPress invoked custom styles. Very nice!

  2. John Faulds responds:
    Posted: February 1st, 2009 at 5:16 pm

    I’ve been doing the custom field link to an external stylesheet with my code examples for a while now, but I like the idea of the striped background (although it seems like it’d be hard to ensure the background lines match the text cross-browser).

  3. Anthony Brewitt responds:
    Posted: February 3rd, 2009 at 10:29 am

    I was just researching for a similar article, you’ve done such a grand job I have just posted a link to this one.

  4. Jonathan Fenocchi responds:
    Posted: February 8th, 2009 at 10:36 pm

    Great tips, Mike. Although (not to nit-pick), the minor problem with using a repeating image background is that the text could be off (it appears to be so in my browser, as a matter of fact). And I have found that scrollbars are typically troublesome and obscure the view in a block of code. But that’s just my experience on it. ;-)

    I use a Wordpress plugin that offers a downloadable version of the code I post, as well as showing the code (with line numbers) and striped background, in monospaced font. Can I get a Green Beast approval? (Shameless plug.) ;-)

  5. Gill responds:
    Posted: February 15th, 2009 at 6:38 pm

    It’s off in Firefox on the Mac as well Mike.

    What I see is

    pre - sits smack bang over the join of the first grey line and the second white line.
    background - sits in the third grey line but it’s a little high. For example the dot on top of the i in images is in the white line above.

    It’s not until I get to overflow that it sits fully on a line and that is the 14th line and it’s white.

    Any help? If not email me and I’ll send you a screenshot. I’ll try it on other machines and browsers too if need be.

  6. shakaran responds:
    Posted: February 19th, 2009 at 10:40 am

    Another tip:
    You should have entry with full rss!

  7. LeoH - Bizarredesigns responds:
    Posted: February 25th, 2009 at 9:14 am

    Just a thought - but I find it easier to post the code as an image (screen shot/script from a favourite editor with all the nice colours, etc.) and then having a downloadable text file linked to the image. For many lines of code, scrollbars can be used.

    Anyway, nevertheless a cool post with a couple of helpful tips as well!

    Thanks man :)

    LeoH

  8. Luigi R. Viggiano responds:
    Posted: March 13th, 2009 at 12:47 am

    I wrote my little tool to format code for my blog, just for my needs (a java developer). It’s far from being perfect, but a many of your tips are respected.
    Just for those who wants to give it a try: http://jrainbow.newinstance.it/sample.html

  9. Thorpe Obazee responds:
    Posted: October 29th, 2009 at 10:57 pm

    I just stumbled on your blog from reading some websites discussing accessibility. Good thing I came here. I never thought of tweaking the code portions of my blog.

    I’ll probably ask you now for permission to use this idea on my posted scripts on my blog.

  10. Thorpe Obazee responds:
    Posted: November 3rd, 2009 at 4:50 am

    Me again. What can you say about highlighted code posted online? Do you think it’s still advisable to place the background when you have colored(highlighted) text in the code? I don’t think it will be as readable as when it wasn’t highlighted.

    Would you prefer highlighted code or the background if you were asked to choose?

    Sorry about asking too many questions ;)

Sorry. Comments are closed.




Note: This is the end of the usable page. The image(s) below are preloaded for performance only.