Add javascript in blogspot (blogger) post

Did you ask yourself why in blogspot posts some javascript code works but in some cases don't. In this article you will find answer.

In HTML\Jscript gadgets jscript code work well. But this is not a case in posts.

For example I added this code to my blogspot post and it didn't working.

<a onclick=javascript:showMessage() href="#" >Test</a>
<script language="JavaScript">
function showMessage()
{
alert("Is working in post?");
}
</script>


So this javascript code was inserted in blogspot post (another method is to put javascript code in external file). If you are interested in jQuery inside blogger post check : jQuery on blogspot post.

I couldn't understand why this code doesn't working in blogspot post but in my HTML editor work.

Later I found that this jscript code works well in blogspot post:

<a onclick="alert('This works')" href="#" >Test</a>


Conclusion is that if you put jscript code inside quote code will work. But I was not satisfied with this because I wanted to use jscript function and reuse function code (for example function showMessage() called from multiple places in post). And I didn't find answer how to put jscript function in quote. Find more blogger tips on this blog!


Somewhere I founded tip to make jscript file with jscript code and put this file on the web. After that call jscript function addressing that file.

It shold look something like this:

<script src="http://snow-effect.googlecode.com/files/snow.js" type="text/javascript">

</script>


I think that this method have too many steps and that is too complicated (you must upload you jscript file somewhere on the web and later call this file from your blogspot post).

After rejecting this method, I take look at my blog source (View source):

<script language="JavaScript">
<br />function showMessage()<br />
{<br />alert("Is working in post?");
<br />}
<br /></script>


There is a problem. In new line. Every time you have new line blogger editor add <br /> tag. Because of this <br /> tag web browser can't execute jscript.

So correct solution for my problem should look like this:

<a onclick=javascript:showMessage() href="#" >Test</a>
<script language="JavaScript">function showMessage(){alert("Is working in post?");}</script>


To work well javascript in blogger post should be in one line.


This is example of JavaScript code that works (click on Test to see):
Test

Check more javascript for blogspot samples:


Related articles:
jQuery on blogspot (blogger) post
Problem with HTML table in blogspot post
Previous
Next Post »