Javascript Validation for assignment

199 views Asked by At

I'm currently trying to validate my website for my assignment but I'm having trouble validating the Javascript I've used. The assignment requires me to stay in xHTML 1.0 Strict while using CSS and Javascript. I have 2 scripts that have problems as I will show below. Any guidance or solutions would be greatly appreciated.

First script:

<script type="text/javascript">
  var imageURLs = [
       "1_to_dtop.png"
     , "2_to_dtop.png"
  , "3_to_dtop.png"
  , "1_to_tablet.png"
  , "2_to_tablet.png"
  , "3_to_tablet.png"
  , "1_to_mobile.png"
  , "2_to_mobile.png"
  , "3_to_mobile.png"
  ];
  function getImageTag() {
    var img = '<img src="';
    var randomIndex = Math.floor(Math.random() * imageURLs.length);
    img += imageURLs[randomIndex];
    img += '\" alt="Product Sneak Peek\" />';
    return img;
  }
</script>
  
  <div id="box"><script type="text/javascript"> document.write(getImageTag()); </script></div>

w3 validator errors:

document type does not allow element "img" here

Second script:

<script type="text/javascript">
var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("slides");
    for (i = 0; i<x.length; i++) {
       x[i].style.display = "none";  
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}    
    x[myIndex-1].style.display = "block";  
    setTimeout(carousel, 5000);
}
</script>

w3 validator errors:

character ";" not allowed in attribute specification list for (i = 0; i

2

There are 2 answers

1
Praveen Kumar Purushothaman On

When you wanna validate JavaScripts, you need to do:

<script type="text/javascript">
  //<![CDATA[
  // Put your scripts here...
  function blah() {}
  //]]>
</script>

A CDATA section is required if you need your document to parse as XML.

This is important for the inline scripts to get validated. This will prevent the validator to validate entities like:

  • & and ;
  • < and >

You can read more about this topic at JavaScript and XHTML and Properly Using CSS and JavaScript in XHTML Documents.

1
Shaun On

Found my solution!

I had to use external javascript files in place of the script.

For anyone who uses this for help, in place of the script use this in your HTML:

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

And then save your Javascript to a new file called

script.js

Change the name of the file and the src path to suit your needs.