Page 1 of 1

A very basic Javascript problem!

Posted: Wed Sep 08, 2010 11:11 am
by srod
Hi,

I don't use Javascript much (and am a complete duffer with it!) but I have a little test function which works fine when embedded in the html itself. However, as soon as I move the routine to an external .js file the damn thing will not load. I get a 'Invalid character... line 1... character 1' error. I even get this error when linking to an empty .js file! I've tried messing around with the EOL characters and BOMs etc. but all to no avail.

Anyone know why this might be happening?

Here's the HTML :

Code: Select all

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>New Page 1</title>
<script language="JavaScript" src="test.js"></script>
</head>

<body>
<span onmousedown="toggleDiv('mydiv');"><img id="mydiv_img" src="collapsed.gif"></img></span>
<div id="mydiv" style="display:none">This is a test!<br>Heyho!</div>
<p>Hello!</p>
</body>

</html>
And here's the JS :

Code: Select all

function toggleDiv(divid){
  if(document.getElementById(divid).style.display == 'none'){
    document.getElementById(divid).style.display = 'inline';
    document.getElementById(divid + '_img').src = 'expanded.gif';
  }else{
    document.getElementById(divid).style.display = 'none';
    document.getElementById(divid + '_img').src = 'collapsed.gif';
  }
}
The routine simply collapses/expands a HTML div etc. As I say, works fine if embedded directly in the HTML.

Thanks.

Re: A very basic Javascript problem!

Posted: Wed Sep 08, 2010 12:06 pm
by Innesoft
It works without a problem here, firebug gives no warnings or errors and I don't see anything wrong with the code itself. BOM/EOL shouldn't be a problem either way.

Tested in FF3, IE8

Try adding... divid.toString() + '_img'.. just to be sure, though you shouldn't need to, as string conversion is done on the fly.

Are you testing this locally or on a remote server? Which browser? Is it a browser error or an IDE error?

Also, this will help you a lot --> http://getfirebug.com/

Re: A very basic Javascript problem!

Posted: Wed Sep 08, 2010 12:26 pm
by srod
Thanks for the reply.

Using IE8 on Vista Premium. Testing locally only.

As I say, I get the same error if the .js file is empty!

Have tested with other .js files I downloaded... same problem. I can see nothing amis with the security settings etc.

Very strange for sure.

Re: A very basic Javascript problem!

Posted: Wed Sep 08, 2010 12:38 pm
by srod
Well, I have changed nothing... but now it is working!

Doh!!! :)

What on Earth is going on here?

Re: A very basic Javascript problem!

Posted: Wed Sep 08, 2010 1:36 pm
by Trond
IE must have cached a bad version of your file.

Re: A very basic Javascript problem!

Posted: Wed Sep 08, 2010 1:37 pm
by srod
Trond wrote:IE must have cached a bad version of your file.
Yes that makes sense... buggered if anything else does mind! :)