Validate with Javascript

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Trying to get a site validated, but not being totally savvy with JS yet, I'm having a headache.

I've got this in a function:
else if (opacity<=0)
The less than sign causes it to be invalid.
"character "<" is the first character of a delimiter but occurred as data"

If I change it to &lt; as W3C suggests, it validates but then the JS that uses that simply doesn't work.

Site is not live so cannot link to it, but can show the entire JS if required.

This was also invalid <SCRIPT language="JavaScript">
I changed it to this<script type="text/javascript"> and the code using that seems to still work ok, just wondered if there are any problems with doing that?

teammatt3's picture

He has: 2,102 posts

Joined: Sep 2003

I always use
<script type="text/javascript">...
There's nothing wrong with that.

The proper way of doing things is putting your JS in a file and including it in your document:

<script type="text/javascript" src="/path/to/js.js"></script>

Another thing I've seen done is something like this

<script type="text/javascript">
<!--
document.write("Something");
//-->
</script>

Comment out your JS with HTML comments (to get through the validator, and prevent non-JS users from experiencing weird stuff).

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Ahh, cheers matt.

The commenting out worked.
I guess it should be done regardless of valid purposes if it prevents potential issues.

He has: 629 posts

Joined: May 2007

You'd use a !CDATA section for XHTML though. (But you knew that...)
http://www.w3schools.com/xmL/xml_cdata.asp

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Well, I'm really not clued up with JS, so I didn't know about that. Will look into that too, cheers.

But as it happens, commenting out the JS allowed it to validate to XHTML Strict and still function correctly in 3 major browsers.

He has: 629 posts

Joined: May 2007

Nothing much to do with JavaScript-- we're talking basic XHTML markup here.
Not that it matters much, since I suspect that every browser on earth treats your pages as HTML, not XHTML.

Of course, if you did send your pages as XHTML, then HTML comments are a good way of hiding the script altogether...
Smiling

Cordially, David
--
delete from internet where user_agent="MSIE" and version < 8;

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.