Dynamic Code Viewing with jQuery

Dabbling around with “jQuery”:http://jquery.com for the last chapter in my “upcoming
book about JavaScript”:http://www.amazon.com/exec/obidos/ASIN/1590596803/onlinetoolsorg/ , I realised it is dead easy to do something that really annoyed the hell out of me for a long time:

When you display code examples in online tutorials and you don’t want to use server side includes to show the code (as you want to offer the explanation page as documentation as well) you need to maintain the code in two locations: The code itself and the code examples in the documentation document.

Now, jQuery has these “really cool methods to do easy AJAX calls”:http://jquery.com/docs/ajax/, why not use them to pull in the code when the user clicks the link to the code?

The “example page for jqueryCodeView”:http://icant.co.uk/sandbox/jquerycodeview/ shows the outcome and the script that makes it happen. Quite neat package, that.

5 Responses to “Dynamic Code Viewing with jQuery”

  1. Ron Says:

    You could add overflow: auto and a width when presenting the code

  2. david Says:

    this is prety cool, only problem i see is most tutorial sites segment the code, meaning they separate out bits and pieces so they can then explain it. be interesting to see this developped to display line by line, so you could say enter a certain page and then grab lines 15-30 or something like that.

  3. Leland Scott Says:

    Chris, this is terrific! I can think of a lot of web pages I’ve done that would benefit from this kind of thing. And you’re right… it makes managing the code much easier.

    On a somewhat related note, I discovered a very cool feature of OmniWeb (I’m using the 5.5 beta release)… In the “Page Info” panel that slides up from the bottom, you can not only see all the downloaded page elements, but for the javascript and css files, you can select “view source,” and they show up in OmniWeb’s terrific source view editor! Of course, OmniWeb isn’t exactly the most widespread browser around, so for everyone else, your CodeView script is perfect!

  4. imran Says:

    This works flawlessly,
    but what if the code to be parsed is in the same file.
    I mean I want to show only a portion of page as code example in the same page.

    Please Reply

  5. Chris Says:

    you’d need to extend the functionality then – just load the same document and use a regular expression to delete what you don’t want to use.

Wait till I come! is the blog of Christian Heilmann , a developer evangelist living and working in London, England. Download vcard.

Feed me, Seymour: Entries (RSS) and Comments (RSS).