(The indentation got crapped on by the editor. Will fix it soon.)
If you work with javascript (+jquery), html and css and always seem to make overly complex and unmaintainable code this little rant is for you :)
The task
Imagine yourself getting the task of creating the most ugly registration form in the world. Let’s call it “the ugly green form”. I’m guessing you would create something like this guy here:
Name
Age
Even if you are creating the ugliest form in the world, you would not implement it using the markup below. Why? Because you care about the separation of concerns and you care about the people maintaining the code in the future.
Don’t do this
<script type=“text/javascript”>
function save() {
var name = $(“#name”).val();
var age = $(“#age”).val();
//do something with the data
alert(name + ” - “ + age);
}
</script>
<table style=“background-color: Lime”>
<tr>
<td>
Name
</td>
<td>
<input type=“text” id=“name” />
</td>
</tr>
<tr>
<td>
Age
</td>
<td>
<input type=“text” id=“age” />
</td>
</tr>
<tr colspan=“2”>
<td>
<input type=“button” onclick=“save();” value=“Save details” />
</td>
</tr>
</table>
We are not doing a good job of separating the concerns here. This page is doing too much. What ? Too much ? Oh yes! This piece of markup contains the structure, the styling and the behavior of the form. We need to split them up.
Heeeeeeeeeeeeeelp meeeeeeee!
The solution is simple. Put the css skinning in a css file. Put the javascript behavior in a javascript file. Put the html in html file. (Also fix up the HTML to use nice clean markup instead of overly verbose table markup.) You end up with something like this:
Html file
<div id=“form”>
<div>
<span>Name</span>
<input type=“text” id=“name” />
</div>
<div>
<span>Age</span>
<input type=“text” id=“age” />
</div>
<input type=“button” id=“submit” value=“Save details” />
</div>
Javascript file
function init() {
$(“#submit”).click(save);
}
function save() {
var name = $(“#name”).val();
var age = $(“#age”).val();
//do something with the data
alert(name + ” - “ + age);
}
..and the CSS file
#form
{
background-color:Lime;
width:200px;
}
#form span
{
width:60px;
float:left;
}
Are we done ? Nope. We’re not. If we wan’t to test the behavior of a form like this, it would be nice to be able to separate the view (html) from the javascript completely so that the javascript code could be tested in isolation. I will write another post about this in the near future.