How to get javascript to validate xhtml

I’ve been updating the CSS and HTML on one of my sites to validate and in the process have had to solve a bunch of little bugs. One bug that proved very difficult to solve at first involved inline javascript. I was using a few lines to create a widget that scrolls down the side of the page as the user scrolls the page (so the content always remains in view).

The tool I was using to validate my code is the W3C Markup Validator and the error I was getting was in response to this snippet of code, I’ve bolded the part that was causing the problem, it’s the little “<” less than carrot: ($(window).scrollTop() <= $(".smartBannerIdentifier").offset({

Here is the exact errors that that the validator was throwing and a screenshot is below:

  • You tried to include the “<” character in your page: you should escape it as “&lt;”
  • You used an unescaped ampersand “&”: this may be valid in some contexts, but it is recommended to use “&amp;”, which is always safe.
  • Another possibility is that you forgot to close quotes in a previous tag.

So my first method to solve was to remove the less than carrot, and that did fix it, but it also made my ad scroll all the way to the top of the page (instead of sticking lower where it was originally placed).

With a little bit of exploration and a good night of sleep I figured out a way to avoid this kind of javascript validation error (and many others). If you are getting validation errors for any inline javascript all you have to do is comment the actual javascript out with <!--

This technique is used by Google on their AdSense code and many other scripts designed to go in the body of HTML documents and it works perfectly, once I commented out the javascript the page validated and I added back in the < symbol to make the script perform correctly.

Here are the steps to fix:

  1. If you have javascript inline in the body of your HTML document such as <script type="text/javascript">var (javascript here);</script>
  2. Use the HTML comment tags <!-- and --> to comment out the javascript but add two forward slashes to the closing comment tag to keep it from rendering ie //–>
  3. The final solution looks like this <script type="text/javascript"><!--var (javascript here);//--></script>

Good luck! I know it can be a pain trying to get your documents to validate but the guidelines will make your pages run smoother and interpret better. For CSS validation use the W3C CSS Validator tool. And yes… I realize this page doesn’t validate yet, too many projects atm :)

One comment

  1. Cool, useful, thanks. Now I can get my javascript to validate properly. Many thanks again.