Exhibit Blog

Thursday, April 20, 2006

Unterminated string literal

So you want to write some JavaScript dynamically on the client side. Sounds a bit ludicrous, but yes in fact there are times when you might want to do this. Let's stick a simple alert into a previously defined element:

<div id="mycontainer">
<!-- Look ma no code! -->
</div>

<script type="text/javascript">
item = document.getElementById("mycontainer");
item.innerHTML = '<script type="text/javascript">alert("Dynamic I am!");</script>';
</script>

What happens? Nothing good! What the hell is an unterminated string literal? Some browsers will blast you for that in the middle of a script - to deal with sloppy markup basically. Here is your solution:

<div id="mycontainer">
<!-- Look ma no code! -->
</div>

<script type="text/javascript">
item = document.getElementById("mycontainer");
item.innerHTML = '<script type="text/javascript">alert("Dynamic I am!");<' + '/script>
</script>

And bam! It works.

0 Comments:

Post a Comment

<< Home