|
JavaScript Tips
XML Menu Builder
Build powerful, client-side DHTML menus using XML for data and CSS for style. No JavaScript data! No having to place list elements on every single page of your website! No plug-ins!
Making JavaScript Compatible with XHTML XHTML is subject to the same syntactical rules as XML. Because of this, an XHTML processor treats the characters < and & as markup, even if they reside inside a <script> block. Since the < and & characters are also used by the JavaScript language, this creates a conflict. When an XHTML processor sees these characters within the JavaScript code of a <script> block, it attempts to parse the JavaScript code as if it were markup, which causes the XHTML parser to fail. You can get around this conflict and make all JavaScript code compatible with XHTML by placing the JavaScript code within a CDATA section. A CDATA section in XML/XHTML starts with the characters <![CDATA[ and ends with the characters ]]>. Any characters within the starting and ending element of a CDATA section are not treated by the XML/XHTML processor as markup, thus preventing a conflict. Here is an example of how to declare JavaScript code within a CDATA section so that it is compatible with XHTML: <script type="text/javascript">//<![CDATA[ alert("<This is compatible with XHTML>"); //]]> </script> Note that JavaScript source code must be placed within the opening and closing elements of the CDATA section. The CDATA section itself should be commented out with a JavaScript single-line comment // as in the example above. This is so that the JavaScript interrupter does not interpret the CDATA markup as JavaScript, which would cause a JavaScript error. JavaScript code that is imported into an XHTML document from an external source file is always compatible with XHTML. So, for example, any code you place into the external file external.js and import into an XHTML file via the src attribute of the <script> tag will be valid. Here is an example of how to import the file external.js: <script type="text/javascript" src="external.js"></script> |