C. Separation of behavior and structureSeparation of behavior and structure is easy to understand: just don't put any JavaScript code in your HTML page. This takes two steps:
Functions in separate fileJavaScript code belongs in the .js file, and not in HTML files. Therefore, this is wrong: <script type="text/javascript"> function doAllKindsOfNiftyThings() { // JavaScript code } </script> </head> <body> <h1>My HTML page</h1> [etc.] But this is right: <script type="text/javascript" src="/books/1/521/1/html/2/nifty.js"></script> </head> <body> <h1>My HTML page</h1> [etc.] // in nifty.js function doAllKindsOfNiftyThings() { // JavaScript code } We'll discuss the technical aspects of <script> tags in 4D. Remove event handlers from HTMLThe second step in separating behavior and structure is to move all JavaScript calls within your HTML to the separate .js file. In fact, 99% of the JavaScript code in HTML pages consists of inline event handlers. Here, the handlers are in the HTML, where they don't belong: <a href="home.html" onMouseOver="mOv('home')" onMouseOut="mOut('home')">Home</a> Instead, define them in the separate .js file: <a href="home.html">Home</a> // in separate .js file var nav = document.getElementById('navigation'); var navLinks = nav.getElementsByTagName('a'); for (var i=0;i<navLinks.length;i++) { navLinks[i].onmouseover = [code]; navLinks[i].onmouseout = [code]; } The script takes the element with id="navigation" (a <ul>, for instance) and accesses all of its links, then assigns onmouseover and onmouseout event handlers to them one by one.
The JavaScript: pseudo-protocolOccasionally you'll see javascript: pseudo-protocol links like the following one: <a href="javascript:doAllKindsOfNiftyThings()">Do Nifty!</a> This complicated and dirty code is secretly meant as an onclick event handler: when the user clicks on this link, we want to execute doAllKindsOfNiftyThings(). Therefore you should remove the javascript: call from the link and replace it with an onclick event handler in the separate .js file: <a href="somepage.html" >Do Nifty!</a> // in separate .js file document.getElementById('nifty').onclick = doAllKindsOfNiftyThings; As to the href, it should contain either a URL that noscript users can follow, or the entire link should be generated in JavaScript. We'll get back to this in 2F.
|