Separating Data, Style and Behavior on Web Pages
One of my favorite sites A List Apart has another great article about using JavaScript on web pages. This article identifies a potential way to separate your XHTML data that contains the content and semantic pages structure, CSS presentation data, and JavaScript behaviours. The described solution is to get JavaScript to attach its own behaviours to XHTML elements by manipulating the page's DOM.
For example with the following XHTML form:
<textarea class=“large” maxlength=“300” required=“true”>
</textarea>
You could add this JavaScript to validate the form without having to embed the JavaScript within the XHTML.
function validateForm()
{
var x = document.forms[0].elements;
for (var i=0;i<x.length;i++)
{
if (x[i].getAttribute('required') && !x[i].value)
// notify user of error
}
}
var x = document.getElementsByTagName('textarea');
for (var i=0;i<x.length;i++)
{
if (x[i].getAttribute('maxlength'))
x[i].onkeypress = checkLength;
}
function checkLength()
{
var max = this.getAttribute('maxlength');
if (this.value.length > max)
// notify user of error
}
For a better understanding have a read of the article.
Links
JavaScript Triggers Article
Posted by Egon Kuster at February 4, 2005 07:30 PM