2006-01-30

Adding javascript to Blogger posts

First off: Blogger does not let you post <script> tags to your blog. (Edit: It does, at least in non-beta, though it warns you about doing so, probably assuming it wasn't done intentionally.) Which is annoying, but perhaps a design choice to prevent code from executing outside of the context of the blog when syndicated through the blog's Atom feed. Or just plain imposing "this should not be in a blog" opinions on bloggers. Whichever.

I'm a bit surprised, though, as we can still use onclick handlers and the like, which I have put to good use once in a while in previous articles to make small in-page utilities and more helpful self-configurable tutorials. Anyway, we can fortunately put javascript code in our blog templates, so for most purposes there are ways of getting around this small annoyance.

A while ago, I was experimenting with posting plain javascript code in Blogger posts with a template that would let external pages include the result as script tags. Not a unique thought, apparently, as Stephane Hamel has institutionalized the practice. And quite cleverly too, using the year part of the post date (minus 2000) for script major version, month number for minors, and page title for script name. Version 1.1 of the Hello World example, thus maps to http://code67.blogspot.com/2001/01/hello-world.html.

The scheme doesn't allow for .0 minors, though; I would have gone for subtracting one from the month number had I devised the system. (Maybe Stephane likes RCS revision numbers, starting at 1.1. ;-)

If you want to do a less elaborate version for inlining code in a blog post, and just want to put the code in the post you are currently writing, rather than pulling it in from an external URL, I would suggest another solution though. Put this block in your blog template:
<script type="text/javascript">
var c = document.getElementsByTagName('code'), s, i;
var junk = /^\s*\46lt;\133\133CDATA\133|]]\46gt;\s*$/g;
for( i=0; i<c.length; i++ )
{
s = c[i].getAttribute('style') || '';
if( s.match( /display[\s:]+none/i ) )
eval( c[i].innerHTML.replace( junk, '' ) );
}
</script>
(ideally in some function run when the onload event has fired) and it will let you use a <code style="display:none"> <[[CDATA[ your javascript code here ]]></code> sections as if they were really <script type="text/javascrtipt"> //<[[CDATA[ your javascript code here //]]></script> tags. They will of course not show up visibly in your feed, nor do any harm there, either.

Happy hacking!

15 comments:

  1. I would like to have a weekly post that lists my favorite finds that I've tagged in delicious. delicious offers some javascript for doing that, but I am having trouble getting it to work in a blogger post. I tried your workaround, but to no avail. I am sure it has something to do with my ignorance of javascript, template modification, etc. I am feeling my way through the dark, letting you guys with more experience lead me. Any ideas on how I can do what I am hoping to do?

    ReplyDelete
  2. If the code you write uses document.write(), it will not work with this work-around, as the code will not be run in the first pass when the document is being rendered, as would an inline script tag. To do that kind of thing, you would have to put the code in a script tag in your blog template instead.

    ReplyDelete
  3. Those methods are cool and very slick.

    But you CAN put a script tag inside a blog post.

    Two things when doing. If you have convert line breaks set to YES, then you have to put the script in without carriage returns or it will get all the br tags inserted on new lines and cause the script to break.

    When publishing, it will initially give you an error saying "tag is not allowed". Check the box that says stop reporting errors for this post and publish again and it will go through and work.

    Whether or not it's a good idea to do this I don't know. But I do it all the time.

    ReplyDelete
  4. Indeed; thanks for mentioning! While the above described method may be good for some things (especially if the Atom feed isn't filtered for sanity), there are cases, such as when needing to use document.write (yourself, or when a scripts written by someone else does), when post processing just isn't viable.

    ReplyDelete
  5. Wow. These are some hard-core JavaScript include hacks. Thanks for the ideas. I am thinking about creating a service where after adding one Javascript include to your blog template, you can attach other gadgets to each post. Sort of like having a configurable toolbar on every post. Have you seen anything like that?

    ReplyDelete
  6. I'm really trying to understand the correct syntax to use. I don't know a lick of java except how to copy and paste the appropriate blocks of code surrounded by the script tags in my html header.

    I want to be able to implement the digg story button (the one with the counter) into each blog post and so I remove the "display:none" style so that it does show, but I know I'm doing something completely wrong. The java I'm trying to run is:

    "[script]
    digg_url = "URL of story on digg";
    [/script]
    [script src="http://digg.com/api/diggthis.js"][/script]"

    I of course us the appropriate carrot arrows instead of brackets.

    ReplyDelete
  7. Just use the code as is, ignoring my hack. The Blogger editor gives you a checkbox to check, stating that you do indeed want that script tag to go in your blog post; click it, and see if it won't just simply work beautifully.

    My hack, should you go down that path, won't let you source external content, just post script statements inside the code block, i e the digg_url = "URL of story on digg"; part of your example, sans surrounding script tags. If you plan on using that in every post of your blog, I'd stick the latter script tag into the blog template somewhere after where the post gets included, and have just this bit in the blog entry itself.

    First choice, not using my hack (as following web standards is better and more portable), but if it annoys the heck out of you with those mandatory double posting to get the checkbox every time, using the code tags instead, enclosing just the bit in bold where my post says "your code here".

    If the Digg code employs the (somewhat deprecated, though unfortunately useful) document.write (I'm guessing it does), you actually can't use my hack, and have to go with the defaults. Wailing at Blogger's doorstep about not wanting the pains sometimes actually does help; they do read their suggestions / feedback input, and sometimes even have the time to act on it.

    ReplyDelete
  8. Thanks for your quick reply.

    Just use the code as is, ignoring my hack. The Blogger editor gives you a checkbox to check, stating that you do indeed want that script tag to go in your blog post; click it, and see if it won't just simply work beautifully.

    Tried this already. Not a thing displayed.

    My hack, should you go down that path, won't let you source external content, just post script statements inside the code block, i e the digg_url = "URL of story on digg"; part of your example, sans surrounding script tags. If you plan on using that in every post of your blog, I'd stick the latter script tag into the blog template somewhere after where the post gets included, and have just this bit in the blog entry itself.

    I wasn't sure exactly where to split the code up, so the first part of it was in each post while the second part was in the template. Here's what displayed when I tried this:

    http://www.copperbarre.com/hot/digg_code_error.gif


    How I split the code up is shown here:

    http://www.copperbarre.com/hot/digg_code_error.gif


    If the Digg code employs the (somewhat deprecated, though unfortunately useful) document.write (I'm guessing it does), you actually can't use my hack, and have to go with the defaults. Wailing at Blogger's doorstep about not wanting the pains sometimes actually does help; they do read their suggestions / feedback input, and sometimes even have the time to act on it.

    I fear this may be true.

    ReplyDelete
  9. Typo: Second link has a 2 in it.

    http://www.copperbarre.com/hot/digg_code_error2.gif

    ReplyDelete
  10. More typos in the link... It's getting way to late here. There is an L missing in CopperBarrel:

    http://www.copperbarrel.com/hot/digg_code_error.gif

    anda

    http://www.copperbarrel.com/hot/digg_code_error2.gif

    ReplyDelete
  11. Drop the script tag in the first example; that purpose is already filled by the code tag and cdata statement combination.

    ReplyDelete
  12. Won't checking this checkbox when creating a post produce lots of errors when republishing the blog?

    ReplyDelete
  13. Typed "javascript blogger" into google because I needed this, your site came up, copied and pasted code, sorted! Thanks very much :)

    ReplyDelete
  14. Where to put this block of javascript code....in template so that it accurs automatically with every post ,or we can copy this code to current blog post ?
    I wanted to put javascript games on my blog..
    thanks

    ReplyDelete
  15. Last time I checked, you wrote script code in Blogger blog posts by using the <script/gt; tag just as usual (see second paragraph, in bold face).

    ReplyDelete