Chapter 40. Separating JavaScript and HTML
Web applications are naturally separated into different layers. The HTML layer is responsible for getting data to the user, the CSS layer is responsible for the visual representation of that data, and JavaScript adds behavior to the page. Despite this separation, developers have a tendency to tie HTML, CSS, and JavaScript together by using inline style sheets or scripts, as well as by using the style and event handler attributes (such as onclick
).
Proof of this is found in this book. In many examples you'll find the use of inline scripts or event handler attributes. It makes explanations and demonstrations easier while at the same time making maintenance a headache. The more tightly you integrate multiple layers, the more work you face when making changes down the road.
Using inline scripts and event handler attributes is technically correct. After all, the examples in this book use them, but their use made the examples harder to maintain and, in the case of errors, fix. Consider the following code as an example:
<form name="theForm" onsubmit="submitFom(event);" /> <script type="text/javascript"> function submitForm(event) { alert("Submitting!"); } </script>
There is an error in this code. But where? Is it in the <form/>
element's onsubmit
attribute or in the JavaScript code? You have a 50 percent chance of picking the correct spot to start debugging, and if you pick wrong you've wasted time. The actual error is in the onsubmit
event handler: ...
Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.