How Do I Run JavaScripts On My WordPress Blog?
Posted August 3, 2008 by Mister Knowitall
Every time I try to cut and paste some JavaScript from a tutorial site or free script site into my blog, it never works. I’ve tried this with a few different JavaScripts, so it would be a huge coincidence if they were all broken. I figure I’ve got to be doing something wrong. But what is it?
Generally the problem is that you’re entering the JavaScript into your blog editor which treats it like text, not like code. Your blog editor is adding HTML like line break tags and paragraph opening and closing tags after various lines within the JavaScript. You won’t see them when you edit your blog post within the blog software, but if you use the “view source” for the actual blog page seen by the public, you’ll see these.
The problem is that these aren’t valid JavaScript. They’re HTML and they cause the JavaScript interpreter to have an error because it sees something it doesn’t understand. The problem is that most browsers have little or no JavaScript debugging capabilities. So instead of returning an error message with useful information about what’s causing problems and where, they either just abandon running the JavaScript and give no error message or give a completely unhelpful error message.
That’s why the scripts you’ve been trying to run haven’t been working. What you need to do is take the code and put it in its own file. Everything between the <script> and </script> tags goes in an external text file that you end with a .js instead of .txt.
I’ve written a “Hello World” script (the script used as the starting point in every beginner’s tutorial on programming) in JavaScript. It prints “Hello World” in bold, 15 point text. It’s one line of code:
document.write('<b style="font-size:15pt;">Hello World</b>');
I then saved that in a file named jshw.js and uploaded it to my blog using the “Add media” uploader that’s been part of the WordPress editor for the last few versions. If you’re running an older version of WordPress, it’s worth upgrading for this alone, not to mention all the security holes you’ll be plugging. Then I just add the following line of HTML code right in my WordPress editor:
<script type="text/JavaScript" src='http://www.answers-that-help.com/wp-content/uploads/2008/08/jshw.js'></script>
And the next thing you know, that Javascript is making my blog page say…
So, when you’re trying to put a JavaScript into a page on your WordPress-powered site, remember that the best way to make sure it will work is to put it in an external file, then source it with a script tag. That way the text formatting functions of your blog software are less likely to mess with and break the javascript code.

