Category Archives: Tutorials

How-tos, tutorials and guides (mainly on how to code for the web).

Relative units and elastic layouts

The astute members in my audience might have realised (if they're reading via a web browser) that the site has recently undergone a bit of a re-jig. Not just on the outside, but also on the inside. As well as using all the nice class features of PHP 5, the site now has a completely elastic layout.

What's an elastic layout? I hear one person cry! It's a new name for a layout paradigm which has been technically possible for a while. Basically, it means that the whole site's layout resizes according to the browser's default text size — not just the text in the site. This is a leap from liquid layouts, as it means that the site effectively zooms in when the browser's font size is increased, and zooms out when the browser's font size is decreased.

This isn't actually that hard to achieve, but few developers that I've seen appear to have picked up on it. Even those who have implemented it have typically left borders and padding with absolute values rather than relative ones. I would argue that this isn't a very good idea. Let's assume (for the sake of argument) that you have a nice big 50" television linked to the Internet viewing an elastic web page which has absolute sizes for the paddings, borders and margins. Looking at the screen from a couple of metres away, and assuming standard margins and paddings of 5px, and borders of 1px in width, the text would almost run together, and the margins, paddings and borders would not be discernible. This can't be good, and this is why I believe that every measurement in an elastic page should be elastic, and use relative units (barring special cases where images have to be used and alignment is critical: as images for the web are almost completely bitmap-based, absolute units still have to be used here).

The most commonly-used unit with which people implement elastic layouts is the em. This unit originated in ye olde typography, and is the height of a capital "M" in the current font face. (Note that it is not the width of the capital "M", as sometimes believed, although this usually applies, as "M"s are usually square in standard font faces.) The em migrated to CSS in the first version of CSS, but hasn't been used too much since (remember debates about relative-vs.-absolute font sizes?).

The main thing to remember about ems is that 1em is equal to the current font size in points. Therefore, 2em is equal to double the current font size in points! :o

The other thing to remember about ems is that they multiply together to generate the final dimensions. So, if you had a parent element with font-size: 2em;, and a child element with font-size: 0.8em;, the final font size would be 1.6em, relative to the parent element's parent (in this example, we can assume that its font size is just 1em). This works exactly the same way for other properties using em units, such as padding or margin, although you must bear in mind that it's always relevant to the parent element's font size.

GET and POST

One of the most basic features of a website is a form. You can use them to send data to a website, search for things, or manipulate the URL. Many less experienced web developers will have heard of GET and POST requests, but what are they really, and what are the differences between them?

To explain them, let's go back to fundamentals. Every time you get a web page from a server, your browser sends an HTTP request to the server, and gets a response. A typical HTTP request to retrieve this site is as follows:

GET /index.php?media=rss HTTP/1.1rn
Host: tecnocode.co.ukrn
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.8.0.5) Gecko/20060731 Ubuntu/dapper-security Firefox/1.5.0.5rn
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5rn
Accept-Language: en-gb,en-us;q=0.7,en;q=0.3rn
Accept-Encoding: gzip,deflatern
Accept-Charset: UTF-8,*rn
Keep-Alive: 300rn
Connection: keep-alivern
Cookie: foo=bar; foo2=bar
rn

I'm not going to explain it all, but basically, it's asking the server for the /index.php?media=rss page on tecnocode.co.uk (second line). All the other lines are there to detail what can and can't be accepted, and how the connection is going to be handled. The whole thing is terminated with a line containing only rn (the UNIX carriage return and newline escape sequences).

It's the first line we're interested in here, as that is the one detailing the fact that this is a GET request. As you can see, GET requests are used to retrieve most pages you download off the web, but you might not realise that they can be used in forms as well.

POST requests are different to GETs, as instead of encoding parameters from the form in the URL, it encodes them in a different part of the request.

POST /index.php?page=login&paragraph=login HTTP/1.1rn
Host: tecnocode.co.ukrn
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.8.0.5) Gecko/20060731 Ubuntu/dapper-security Firefox/1.5.0.5rn
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5rn
Accept-Language: en-gb,en-us;q=0.7,en;q=0.3rn
Accept-Encoding: gzip,deflatern
Accept-Charset: UTF-8,*rn
Keep-Alive: 300rn
Connection: keep-alivern
Cookie: foo=bar; foo2=bar
Content-Type: application/x-www-form-urlencodedrn
Content-Length: 28
rn
username=DrBob&password=test

You can see here that this request is basically the same as the GET request above, apart from a few minor things. Firstly, the first line says POST instead of GET, and secondly, there are some extra lines at the bottom. Content-Type and Content-Length tell the server the type (encoding) and length of the form data, respectively, then the form data itself is sent; in this case, my username "DrBob", and a fictitious password "test". It's because of this separation of the form data from the URL that POST pages can't be referenced by URL, as a GET request would miss out the POSTed form data.

The next step in understanding, is how to use both GET and POST requests in forms. You can already make a GET request by using a hyperlink, but that doesn't enable you to query the user for their input to the URL's parameters.

<form action="http://tecnocode.co.uk/" method="get">
	<fieldset>
		<legend>Search terms</legend>
		<label for="query">Enter your search terms. You can "-exclude" keywords.</label>
		<input type="text" name="query" id="query" value="" />
		<input type="hidden" name="page" value="search" />
	</fieldset>
	<fieldset>
		<input type="submit" value="Search" />
	</fieldset>
</form>

Here we have a simple search form, which uses GET. The main difference between this and a POST form is that the method for a GET form is "get". However, there is another difference, and that's that if you try to put parameters on the URL in the action attribute, they will be ignored. With GET forms, all parameters must be done as <input /> fields; that means moving any action parameters to hidden inputs, as is shown in the example. If that example was used with a query of "moo", the URL "http://tecnocode.co.uk/?page=search&query=moo" would be returned.

<form action="http://tecnocode.co.uk/?page=login&paragraph=login" method="post">
	<fieldset>
		<legend>Username</legend>
		<label for="username">Your unique username.</label>
		<input name="username" id="username" type="text" value="" />
	</fieldset>
	<fieldset>
		<legend>Password</legend>
		<label for="password">Your personal password.</label>
		<input name="password" id="password" type="password" value="" />
	</fieldset>
	<fieldset class="submit">
		<input type="submit" value="Login" />
	</fieldset>
</form>

This form makes a POST request with login details, because its method attribute is "post". With POST forms, parameters can be put into the action URL, because the form data itself will be submitted separately from them. When used with the username "DrBob", and the password "test", this form will generate the POST request used as an example further up. Note that no inputs are ever securely encoded: the password field is transmitted in plain-text, because this form only operates over HTTP, as opposed to HTTPS; SSL certificates (which are required for HTTPS to work) cost lots of money.

So when should you use POST, and when should you use GET? Well, the best way to remember, is that POST requests should change the state of the server. By that, it is meant that they should trigger some action which will result in future page requests returning pages which are different to those returned before the POST. A good example of this would be to add a news item to a site. GET requests are used for every hyperlink in a site, but they shouldn't be limited to those. For example, if you have a search function on your website, you will most likely want a search form to feed it. However, this form should not use POST! It does not change the state of the server, and thus should make a GET request. Another effect of using GET requests for tasks such as these is that the user's browser doesn't prompt them if they want to re-submit the data when they refresh, and they can bookmark/share the URL of the returned page without it appearing differently for other people.

Some common situations for using GET forms follow:

  • Search
  • Selecting something to view/edit/delete/etc. out of a list
  • Navigating pages (pagination)
  • Selecting the page's stylesheet/view mode (e.g. switching to debug mode on a large web application)
  • Selecting a file mirror for a download

Although it's probably obvious, a list of common POST form usages follows:

  • Adding/Editing/Deleting an item
  • Logging into a site
  • Logging out of a site (yes, this changes the site's state)
  • Submitting a comment or trackback

Just remember: POST changes the server's state. ;)

Getting on form

A lot of sites use forms; it's an ideal way to submit information (how else are you supposed to do it?), but how many actually use forms properly? How many have semantically-correct markup?

Let's start by looking at the elements you should use in a form:

  • <form>
  • <fieldset>
  • <legend>
  • <label>
  • <input />
  • <textarea>
  • <select>
  • <option>
  • <optgroup>
  • <button>

When used properly, these create forms which are both accessible and semantically correct, so other computers can extract information from the forms' markup. However, most websites only make use of a subset of this list of elements, with usually only five elements being used:

  • <form>
  • <input />
  • <textarea>
  • <select>
  • <option>

You'll notice that the <fieldset>, <legend> and <label> tags are missing, and that's what makes most forms poor.

The <label> tag is the easiest to add, and solves most of the accessibility problems associated with badly-coded forms. As the name suggests, it provides a label for a form control, but this label is associated with the element through the use of the for attribute, so that when a user clicks on the label, focus will be given to the associated form control.

<label for="example_input">This is an example input, using the <tt>&lt;input /&gt;</tt> element.</label><input id="example_input" type="text" value="Example input" />

You have two options when using a <label> element. The first is to write a short label (e.g. "Example input" for the above markup), and the second is to write a longer and more informative label (e.g. what's in the above markup). As far as the specifications go, neither is incorrect. Personally, I believe the latter is the better, as it provides more help as to how to use the form control, and a simple label can be provided by the <legend> tag, which is discussed later.

One thing many web developers do when using labels is to place the associated form control inside the label, after (or before) the label text. Although this is permitted by the specifications, it provides no advantage, and just makes the markup ungainly. :(

The <fieldset> element is next on the list, and it's quite important. It allows form controls to be grouped together in logical sections.

<fieldset>
<label for="example_input">This is an example input, using the <tt>&lt;input /&gt;</tt> element.</label><input id="example_input" type="text" value="Example input" />
</fieldset>

How you group form controls is very much your own choice. Personally, I stray a little on the wild side and usually assign a fieldset to each form control. This is perhaps segregating them too finely, and is something I should work on to change. One example of a good group would be "Personal details".

Fieldsets by default appear without a label, which isn't very helpful to users, and isn't very good for accessibility (screenreaders don't know anything about the grouping), so you can use the <legend> element to assign a label to a fieldset, much like a <label> assigns a label to a form control.

<fieldset>
<legend>Personal details</legend>
<label for="example_input">This is an example input, using the <tt>&lt;input /&gt;</tt> element.</label><input id="example_input" type="text" value="Example input" />
</fieldset>

The <legend> tag must come directly after the opening part of the <fieldset> tag, or it is invalid.

Another little-used form element is the <optgroup> element. It's old, dating back a long time, but not many people are aware of its existence (or if they are, they don't use it). It's used to group <option> elements together logically in a selection list.

<select id="example_select">
<optgroup label="First group">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
</optgroup>
<optgroup label="Second group">
<option value="3">3</option>
<option value="4">4</option>
</optgroup>
</select>

The option group's label value is required, and specifies the label to display as the title for the group.

The final element most authors don't use is the <button> element. I must confess that I didn't know much about it until I read the W3C's definition:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

Visual user agents may render BUTTON buttons with relief and an up/down motion when clicked, while they may render INPUT buttons as "flat" images.

The <button> element offers rich possibilities, but you must always remember the accessibility concerns when using it. Would a screen reader read content which is inside a button? Common sense should prevail.

The final point to make about form authoring is that of ease-of-use. It it just about always in one's interest to make a form as easy to use as possible, and just by using the accesskey and tabindex attributes a complex form can be easy to use.

The accesskey attribute can be applied to:

  • <a>
  • <area />
  • <button>
  • <input />
  • <label>
  • <legend>
  • <textarea>

The character (from the document's character set) in the attribute value will – when pressed – give focus to the element. This doesn't have to just be used for form controls; you could give the access key of "H" to a home link. However, form controls are the main use of accesskey. In my opinion, it's best to be careful with your use of access keys, applying them only to general elements such as the "Submit" and "Reset" buttons to cut down on maintenance when you come to add to the form.

The tabindex attribute can be applied to:

  • <a>
  • <area />
  • <button>
  • <input />
  • <object>
  • <select>
  • <textarea>

The number in the attribute specifies the tab order of the element, with lower numbers coming before higher ones (except "0", which puts the element last). Elements with identical tab indexes will be focussed in the order they appear in the markup. Usually there's no need to change the tab order of elements in a form, as it's usually calculated properly by the browser, but in some cases (especially if you're moving things around a lot with CSS) it's necessary to intervene and change the tab order manually.

That's it. If you knew how to make decent forms before, the information here should enable you to write splendid ones. :)

JavaScript: AJAX

Continuing in my series of articles on my JavaScript library, I am doing my second article about my AJAX JavaScript file. The first article was written right at the start of the AJAX craze, and was (in hindsight), rather badly written. The JavaScript provided with it was too, quite badly written, and I've since revised my JavaScript (without telling anybody) several times. This morning, version 2.0.0 landed safely in my private SVN repository, and it is this that I am going to talk about.

Since the first version of my AJAX code, two major changes have been made (and many minor ones). The first change was to abolish the awful <resultpos> idea, splitting each function in two (i.e. when adding a comment, instead of having the same function called on the client side originally and when the data packet is received from the server, two separate functions would be called). The second major change was completed only recently, and has enabled multiple simultaneous requests to be made without fear of the packets getting mixed up.

Also present in this version is new functionality in the form of AJAX popovers. No longer are complete pages limited to being loaded through an HTTP request; using the popover functions in this script will enable you to have pages load as popovers on top of the current page.

This functionality isn't meant to be used for advertising (certainly not!), but the terminology was too good to lose. Imagine a scenario where you have a user who wants to log in, but making a complete HTTP request is just too much of a drag for them, and it's flashier to do it using that wonderful buzzword: AJAX. The user clicks the "Login" link, and instead of a new page loading, and them losing where they were in the current page, a popover appears with the username and password inputs. The user duly enters their details and clicks "Login", to have the login popover fade out, and their login to be authenticated.

Admitted, it doesn't have a massive range of uses, but it certainly is good for adding that "wow" factor to a website or application.

So…on to the script file itself. The script doesn't require any other files for pure AJAX usage, but if you want to use popovers, you'll need to include my general JavaScript library, and if you want fading, you'll need to include the GUI script file I previously wrote about.

To include the script in your page, you'll need to add the appropriate tag to the <head> tag of your document:

<script type="text/javascript" src="http://tecnocode.co.uk/sources/client/ajax.js" />

However, this file on its own won't really get you anywhere: you still need some CSS to prettify the popovers, and another script file to contain implementation-specific AJAX JavaScript. This file, you'll have to write yourself (typically producing ajax_custom.js), but I've provided some CSS already, which can be included by placing the following line in your <head> tag:

<link href="http://tecnocode.co.uk/sources/client/ajax.css" rel="stylesheet" media="all" type="text/css" />

Use of the script is quite simple. To initiate an AJAX transaction, simply call the load_XML_doc() function, passing the URL you want to load (with any data you want to pass as escape()d GET parameters) as the only parameter. The function will perform the transaction, calling the JavaScript callback function specified in the packet when the XML data packet is received.

Each XML packet must be in the following format:

<response>
	<method>[callback function name]</method>
	<result>[result markup]</result>
</response>

This latest version of my code also supports messages and errors returned by the server, using the first following XML packet for messages, and the second following XML packet for errors:

<response>
	<message>[message text]</message>
	</response>
<response>
	<error>[error code or name]</error>
	<message>[error message text]</message>
</response>

Errors and messages are handled transparently by the AJAX code, so implementation-specific code need not worry about it.

Speaking of implementation-specific JavaScript, it is a bit of a hazy subject, so an example would be in order. The example I'll use is the AJAX comment submission code form this very website, which requires several of my JavaScript libraries not previously explained. You'll just have to live with that.

Implementation-specific JavaScript is split into two functions: a function called to build the request URL and initiate the transaction, and a function to be called when the XML packet is received from the server.

This first function takes six parameters, specifying the details of the comment: author, email, comment, rating, post_id, parent_comment. The function is called in place of submitting the comment form, with the last two parameters hard-coded into the markup by the server:

function add_comment(author,email,comment,rating,post_id,parent_comment)
{
	//Take the specified input, and make the query
	if(!check_form(form)) return false;
	var url="./index.php?media=xml&page=blog&paragraph=add_comment&id="+escape(post_id)+"&parent_comment="+escape(parent_comment)+"&author="+escape(author)+"&email="+escape(email)+"&comment="+escape(comment)+"&rating="+escape(rating);
	load_XML_doc(url);
	return false;
}

Note that the function also calls check_form, to make sure all the fields are filled in correctly. This function is from my form validation JavaScript, which I hope to write about in the future.

So, this function has started the request, and now the client is waiting for news of the packet. Usually, this will be very fast (that's why I decided not to put an activity indicator on the page), but sometimes it won't; you might want to consider putting a little activity indication "throbber" into pages when using AJAX.

The server processes this request. In this case, it takes the comment data which has been submitted (notice that it was all escape()d), checks if it's all valid, and if so, writes it to the database. It then returns an appropriate XML packet, with a <method> of add_comment (not add_comment_response: the "_response" is added on the client-side). add_comment_response is then called:

function add_comment_response()
{
	//Response mode: parse the response, and see what the server says about our submitted comment
	//Our <result> will be the HTML for the comment (boolean)
	if(AJAX_RESULT)
	{
		//Display the comment, remove a class="no_x" element (if applicable) & clear the form fields (make sure we don't clear locked ones)
		var container=document.getElementById("comments_container");
		var comment_form=document.getElementById("comment_form");
		var i,random_id,cloned_child;
		var elements=getElementsByClassName(container,"no_x_comments");
		for(i in elements)
		{
			random_id=assign_random_id(elements[i]);
			fade_object(random_id,0.1,20,false);
			setTimeout("document.getElementById('comments_container').removeChild("+random_id+")",240);
		}
		for(i=0;i<AJAX_RESULT.childNodes.length;i++)
		{
			cloned_child=AJAX_RESULT.childNodes[i].cloneNode(true);
			if(cloned_child.style) cloned_child.style.opacity=0;
			container.appendChild(cloned_child);
			if(cloned_child.style)
			{
				random_id=assign_random_id(cloned_child);
				fade_object(random_id,0.1,20,true);
				wait(240);
			}
		}
		clear_form_inputs(comment_form);
	}
	else
	{
		window.alert("Your comment was rejected by the server. Please amend any errors and try again.");
	}
}

This function isn't passed any parameters. (Perhaps it should be? I'm looking into revising this functionality sometime in the future.) It accesses the global variable AJAX_RESULT to see what's there. In this example, the result contains all the markup for the submitted comment, so that it can just be popped (using the DOM) into place after all the other comments in the page.

Half of the complexity of this function is due to the use of fading from my GUI JavaScript, and the use of the DOM to insert the retrieved markup into the document instead of using outdated methodologies such as innerHTML.

Another feature of version 2 of my AJAX JavaScript is the popover functionality. It allows you to create popovers to perform tasks related to (or required by) the current page without refreshing.

The markup for the popups is retrieved when required from the server, reducing the amount which has to be initially downloaded. For example, you could have a "Login" link, which has an onclick handler as follows:

<a href="./?page=login" title="Follow this link to login." id="login_link" onclick="Javascript: return load_XML_doc('./?page=login&ajax');">Login</a>

Without JavaScript, it just takes you directly to the login page, but if you have a capable browser, it loads up a special version of the page (encased in one of the previously-described XML packets) through AJAX.

The return packet would have a <method> of "login", which would call the first of the two custom JavaScript functions required to do a popover (you can cut this down to one function if it's a non-interactive popover, such as a message):

function login_response()
{
	//Instantiate a popover
	if(AJAX_RESULT)
	{
		var login_link=document.getElementById("login_link");
		var x_pos=findPosX(login_link);
		var y_pos=findPosY(login_link);
		if(AJAX_RESPONSE.getElementsByTagName("redirect")[0])
		{
			setTimeout("window.location='"+AJAX_RESPONSE.getElementsByTagName("redirect")[0].textContent+"';",2000);
		}
		do_ajax_popover("Login",AJAX_RESULT,x_pos,y_pos);
	}
	else
	{
		window.alert("The server could not return the login form. Please try again.");
	}
}

This code is called once the markup has been retrieved from the server, and works out the position at which to spawn the popover, then spawns it. In this example, the position is worked out as the position of the login link the user followed, but other things may be done.

The popover has now been displayed; what to do now? Well…you'd want to have the login carried out through AJAX too, just to capitalise on the situation. This can be done. :)

The first child node of the popover is always given a special attribute: popover_id. This contains the unique ID of the popover containing the markup, so that multiple popovers can utilise the same JavaScript simultaneously without getting tangled. In this example, the login form calls a JavaScript function (do_login) instead of being submitted normally, although it can fall back to that if required:

function do_login()
{
	if(document.getElementById("login_form").getAttribute("popover_id"))
	{
		var url=document.getElementById("login_form").getAttribute("action")+"&ajax&username="+escape(document.getElementById("username").value)+"&password="+escape(document.getElementById("password").value);
		load_XML_doc(url);
		close_ajax_popover(document.getElementById("login_form").getAttribute("popover_id"));
		return false;
	}
	else return true;
}

This is basically just another URL-generation function, with the addition of a call to close_ajax_popover with the popover ID to close the popover after the login data has been submitted. Once the return packet arrives for this request, it will call login_response again (as it will have a <method> of "login"), but it will also have a <redirect> tag present, which will redirect to the logged-in page after it has displayed the message which was returned by the AJAX request. It's a bit of a mouthful to get your head around. ;)

I have put together a small sample page showing popovers in a little more detail (i.e. interactively).

Now for a more technical view of the functions:

Function declaration Description
public bool load_XML_doc(string url) Request the specified URL through an XMLHttpRequest object. Return false on success, and true on failure (for events).
private void process_request_change() Processes a data packet received from the server after a request.
public bool do_ajax_popover(string title_text,dom_tree snippet,int x_pos,int y_pos) Create a popover and make it appear in the page.
private void _close_ajax_popover(dom_event event) Destroy a popover after the "Close" button has been pressed.
public void close_ajax_popover(string popover_id) Destroy a popover by ID.

The CSS is quite simple, and all the classes and IDs generated by the Javascript already have a rule in the CSS file. I have provided a brief explanation of each class, and an image to depict what it is:

Class / ID Description Applicable element(s) Descriptive image
.popover_container The main popover "window" element. <div> .popover_container
.popover_content The content in the popover, retrieved from the server. <div> .popover_content
.popover_bottom A currently unused element at the bottom: could possibly be used for a "tail". <div> .popover_bottom
.popover_title The popover's title. <h2> .popover_title
.popover_close The "Close" button. <a> .popover_close

If you do use this script, please download it and host it with your website; do not leech my bandwidth! Additionally, please follow the terms of the license to the letter. I hope this is of use to somebody. :)

JavaScript: GUI

Following on from my article on JavaScript popup messages, I am going to try and get through my entire JavaScript library, releasing it to the public. This is a good thing all round, as I get to improve my JavaScript to bring it up to release quality, and then it gets released. :)

This script file is the GUI library. Although there are many functions for dealing with the interface in other script libraries, the functions in this file are the most so, and aren't relevant to anything else.

It doesn't require any other library files, although having it as the only library file won't get you anywhere quickly, so it would be best to include my general library first, by putting the following markup in your <head> tag:

<script type="text/javascript" src="http://tecnocode.co.uk/sources/client/general.js" />

The next step is obviously to include the GUI JavaScript itself, which is best left untouched, but that's by no means absolute:

<script type="text/javascript" src="http://tecnocode.co.uk/sources/client/gui.js" />

Currently (January 2006), there are only three functions in the file: a function to fade things in and out, and two functions for retrieving the position of an element. These two functions aren't actually mine; credit for them must go to quirksmode.org, although I'll probably customise them in the future.

To fade an element in, you must first set its opacity to 0:

element.style.opacity=0;

Then, you can use the fade_element function to gradually fade the element in:

fade_object(element.getAttribute("id"),0.1,10,true);

This function call increases the opacity of the specified element ID by 0.1 (10%) every 10 milliseconds. Note that after calling this function, execution continues in the current function (i.e. the fading starts in a new thread), so if you have code after the call to fade_object which depends on the fade, you'll have to delay it somehow.

It is just as easy to fade something out: you just need to set the fourth parameter in the call to fade_object to false; this decrements the element's opacity by the specified amount at the specified frequency, instead of incrementing it. Bear in mind that you'd have to set the element's opacity to 1 before fading it out, instead of setting it to 0.

Whilst calling the JavaScript in this manner is backwards-compatible, the title of the message is just "Message", and you cannot pass DOM snippets in — only plain text can be passed as the function parameter.

The two other functions are designed to retrieve the position (left and top, respectively) of a specified element on the page.

If I wanted to find the X-position (distance from the left-hand edge of the rendering area) of an element, I'd make the following function call:

var left_distance=findPosX(element);

I could do a similar thing to find the distance from the top of the rendering area:

var top_distance=findPosY(element);

Now for a more technical view of the functions:

Function declaration Description
public void fade_object(string fade_element_id,float add_opacity,int frequency,bool increasing_opacity) Fade the specified element in or out. This function doesn't return anything, and spawns a new thread for its execution.
public int findPosX(dom_element obj) Finds the distance from the left-hand edge of the rendering area of the specified element.
public int findPosX(dom_element obj) Finds the distance from the top edge of the rendering area of the specified element.

If you do use this script, please download it and host it with your website; do not leech my bandwidth! Additionally, please follow the terms of the license to the letter.

JavaScript: popup messages

With the recent batch of changes to the site, I've introduced a number of my new JavaScript files to the domain. I feel that they're too good to be kept to myself, and as such, they're released under the GPL. The first one I'm going to talk about is the popup message JavaScript, which replaces the standard browser message popup with a custom XHTML one.

A JavaScript popup message in use on drboblog.Now I'm not usually one to replace browser features, as I believe that the browser and the web page should be kept separate, much as the structure and the presentation should be kept separate. However, when it comes to browser message popups, there really is no alternative but to replace them. They're ugly, unskinnable, and can really ruin what would otherwise be a good page.

So to replace the browser popup windows, I've written a Javascript file. It has functions for creating, controlling, and controlledly-detonating custom XHTML message popups, and replaces the standard browser window.alert("message"); function when included in the page. When activated, it disables all the links and forms in the page below it, and re-enables them when dismissed.

The code is pretty simple, and most of it is just bulk to generate and manipulate elements in the DOM, so it doesn't need explaining. However, I feel the usage of the code does require some explanation, and presents a nice opportunity for another example page.

To begin with, you must include my standard JavaScript library file, which is also available under the GNU GPL. This is accomplished using the following XHTML in the <head> tag of your page:

<script type="text/javascript" src="http://tecnocode.co.uk/sources/client/general.js" />

The next step is obviously to include the popup message JavaScript itself, which I would appreciate if you left in its original form, but since that's not a requirement of the license, you don't have to: :P

<script type="text/javascript" src="http://tecnocode.co.uk/sources/client/popup_message.js" />

This, too goes into the page's <head> element, but after the inclusion of the general library. On my website, I have moved site-specific popup message functions into a separate popup_message_custom.js file and included it, but this is by no means a requirement.

The final inclusion is of the CSS file. This file should obviously be customised to your own tastes and site design, but the default design is pretty neutral. This is included with the following markup (once again in the <head> section):

<link href="http://tecnocode.co.uk/sources/client/popup_message.css" rel="stylesheet" media="all" type="text/css" />

Now we get onto the actual calling of the functions necessary to create a popup message. You can call the following function anywhere you like to create a popup message, but a sensible place to put it would be in the onclick event of a link, or something else:

popup_message("window_title",message);

Here, you would obviously replace window title with the popup message's required title, and message with the message you want, which should be a JavaScript DOM snippet. Alternatively, you can pass a string, but this is messy. You should note that this function always returns false, to facilitate the cancelling of events.

However, in some circumstances, you might not know if the file has been included or not, and in any case, for backwards-compatibility, it is preferable to use the window.alert("message"); function instead of the script-specific function described above:

window.alert("message");

Whilst calling the JavaScript in this manner is backwards-compatible, the title of the message is just "Message", and you cannot pass DOM snippets in — only plain text can be passed as the function parameter.

Now that the details of using it have been cleared up, let's finish off with a slightly more technical description of the JavaScript functions, and the CSS:

Table 1: popup_message.js functions
Function declaration Description
public bool window.alert(string message) The original, unmodified browser popup message creation function, or a reference to popup_message("title",message); if popup_message.js has been included. Always returns false.
public bool popup_message(string window_title, dom_tree|string message) The custom popup message creation function, which creates a whole new element tree, and displays it on the page. Always returns false.
private void hide_popup_message(dom_event event) The function to destroy (remove) a visible popup message. It should not be called by any custom code unless you really know what you're doing.

The CSS is quite simple, and all the classes and IDs generated by the JavaScript already have a rule in the CSS file (although you could have styles for individual popup message IDs, but this is going too far). I have provided a brief explanation of each class, and an image to depict what it is:

Table 2: popup_message.js classes and IDs
Class / ID Description Applicable element(s) Descriptive image
.popup_message The main popup message "window" element. <div> .popup_message
.popup_message_title The title of the popped-up message. <h2> .popup_message_title
.popup_message_message The container for the message. <div> .popup_message_message
.popup_message_button The "OK" button used to dismiss the popup message. <button> .popup_message_button

A final note must be about the files I've provided. If you do use this script (and the CSS), please download it and host it with your website; do not leech my bandwidth! Additionally, please follow the terms of the license — I'm giving you something, and I only ask for a little in return.

Semantic web design

Semantic design is one of the many buzzwords floating carefree around the internet at the moment. Admittedly, it's not the biggest (that must be Ajax at the moment), but it is quite a good word. However, not many people know what is actually is.

The semantic web design I'm talking about is not part of Tim Berners-Lee's new semantic web, but it's related. The semantic web is an initiative to write new pages in a language based on RDF, which allows computers to extract the meaning from web pages. The semantic web design I'm talking about is the proper use of XHTML tags, to structure a page sanely. However, this also allows computer to "read" web pages, to a certain extent.

All the original HTML tags were created and designed to structure information, not to format it. However, since the explosion of the internet, this border was blurred by masses of ineducated poops, and HTML turned into a pea-soup of a formatting language. The W3C decided that this wasn't good enough, so they created XHTML. It was designed to be similar to HTML, but with all the extraneous formatting tags removed. The markup was semantic, and XML-compliant.

However, even when using XHTML, people somehow find ways to abuse the semantics, and use tags inappropriately. This article is trying to stamp that out.
Let's take a look at some markup for a sample page which has been written by a non-semantically-aware author. Concurrently, we'll look at the same page with good semantics. Both pages validate perfectly, yet the bad example is so much worse than the good one. Why?

Both examples start with the same valid markup - the DOCTYPE and the opening <html> and <head> tags:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB">
<head>

After this, it starts to go wrong. The bad example puts bad data into the <title> element:

<title>:) DrBob's amazing page :)</title>

This is not acceptable, as – although nothing strictly semantically incorrect has been done – the two smilie faces (":)") should not be in the title, as they are nothing to do with the page title, and are just confusing — semantics doesn't just cover the usage of tags, it also covers the contents of said tags.

The code should be written as follows; with the smilies removed:

<title>DrBob's amazing page</title>

Following that, some bog-standard code follows. However, the bad example has still managed to mess it up – even the simplest of code can be semantically incorrect:


<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="keywords" content="bad semantics,web design,web development,XHTML,semantic web" />
<meta name="author" content="Philip Withnall" />
<meta name="description" content="A page to teach about how not to do semantics in web design. Woo! I'm such a cool web designer! Pick me! Woo! (@Google: This mad text is all in the name of education.)" />

You'll notice the crazy content in the meta description tag: it's semantically incorrect. In a meta description tag, you should only include data relevant to the description of the page, not (as in this case) a very modest description of self.

Cleaned up, the code is as follows:


<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="keywords" content="good semantics,web design,web development,XHTML,semantic web" />
<meta name="author" content="Philip Withnall" />
<meta name="description" content="A page to teach about how to do semantics in web design." />

The next block of code in the bad example is quite interesting, and gives us an insight into why semantic web design is better:


<style type="text/css">
.title
{
font-size: x-large;
font-weight: bold;
}

h1,h2,h3,h4,h5,h5,address
{
/*Bah! I had to make these display inline to make them display right! Stupid W3C can't get anything correct!*/
display: inline;
}
</style>

We can see that the author's bad semantics have cost him appearances, as his incorrect use of heading tags (see below) meant that his page didn't display properly without CSS "enhancements". Any mildly-competent CSS coder would know that if you're making heading tags display inline, there's something seriously wrong.

Just for comparison, what follows is the CSS for the good example. Most of it can be eliminated or put into inline style attributes, however, as it's just to make the good example render similarly to the bad example:


<style type="text/css">
.italic
{
font-style: italic;
}

.bold
{
font-weight: bold;
}

.large
{
font-size: large;
}

.strikethrough
{
text-decoration: line-through;
}

.float_left
{
float: left;
}

.float_right
{
float: right;
}

.indent
{
padding-left: 20px;
}
</style>

The next block of code is completely correct, and parses fine, but the author of the bad example has made one of the worst (and unfortunely, most common) mistakes related to semantics: he's used a heading tag incorrectly:


</head>
<body>
<div class="title">DrBob's amazing page <h1>lolzorz</h1></div>

Heading tags are supposed to be used to logically structure the document, with logical headings of a short length in a tree-structure. Starting with the primary header tag is of the utmost importance, but the whole title must be in the tag, not just some small (and irrelevant) part of it. Cleaned up, the code is as follows:


</head>
<body>
<h1>DrBob's amazing page</h1>

The next section of text doesn't look too bad, but there are some mistakes, and some more offending with headers:


<div>I live at <address>Buckingham Palace</address> in <strong>England</strong>. Aren't I <h4>lucky</h4>! Whee!</div>
<p>My name is DrBob, and <em>I</em> come from <em>behind you</em>.</p>

The first offense is the encapsulation of text in a <div>. This element is for logically grouping sections of a document for styling or other purposes. It is not designed to contain text; for that, you should use a paragraph element. The next error is the use of the address element. Although its use is debatable, the official W3C HTML specification states that the address element should be used to encapsulate contact information for a web page, or a significant part of a web page, not somebody's postal address, unless it is their preferred contact medium with regards to the web page. Other errors in this section are regarding the use of emphasis and strong elements. These elements are not to be used with the mindset that "it's going to make the text italic", or "it'll make the text bold"! They should be used to signal emphasis on a section of text which would be emphasised if the text was read aloud. Although people would often make text italic or bold when that is applicable, it is probably not applicable in these circumstances, so the effect should be achieved using CSS. The final mistake in this section is the incorrect use of a level-4 heading. It can't be stressed enough that headers are to be used for logical document section titling, and certainly not for text sizing and font choices!

Corrected, the section is much easier to read:


<p>I live at <span class="italic">Buckingham Palace</span> in <span class="bold">England</span>. Aren't I <span class="bold">lucky</span>! Whee!</p>
<p>My name is DrBob, and <span class="italic">I</span> come from <span class="italic">behind you</span>.</p>

The next section is incorrect from the outset, as the author has chosen to indent it all using a blockquote element, instead of styles:


<blockquote>
<!-- Bah! I had to change it from a <p> to a <div> to get it to validate! Oh well. They're the same to me, anyway, because I know best. -->
<div>Look at my wonderful indented text! Aren't I so <h2>good</h2> at <abbr title="HyperText Markup Language">HTML</abbr>!</div>
<p>I know this page is <a href="http://validator.w3.org/check?uri=referer">valid <abbr>XHTML</abbr></a> and uses <a href="http://jigsaw.w3.org/css-validator/?check=referer">valid <acronym>CSS</acronym></a>. Aren't I <strong>so good</strong>!</p>
</blockquote>

The use of the blockquote element is bad, as the blockquote element should be used to denote long quotations, not to indent things.

In this section, there are also more examples of header misuse, and <div> tag misuse. There is also something else, which hasn't been seen before, and that's misuse and confusion over the abbreviation and acronym elements. The abbreviation tag should only (naturally enough) be used for abbreviations, so its use here to explain what "HTML" means is completely incorrect. The other two uses of acronym and abbreviation elements are also incorrect, as you should always specify a title attribute when using either element (and the author has used the wrong tag for HTML again).

Here's a clean version of this section:


<div class="indent">
<p>Look at my wonderful indented text! Aren't I so <span class="bold large">good</span> at <acronym title="HyperText Markup Language">HTML</acronym>!</p>
<p>I know this page is <a href="http://validator.w3.org/check?uri=referer">valid <acronym title="eXtensible HyperText Markup Language">XHTML</acronym></a> and uses <a href="http://jigsaw.w3.org/css-validator/?check=referer">valid <acronym title="Cascading StyleSheets">CSS</acronym></a>. Aren't I <span class="bold">so good</span>!</p>
</div>

By now, you'll be getting sick of this author misusing headers, so we'll skip that error in the next section:


<h3>Did you know I'm so good at HTML, I can make <del>text strikethrough</del>? Isn't that cool?!</h3>

Apart from the header misuse, there is only one problem with this section, and that's the incorrect use of the <del> tag. It is supposed to be used to indicate that a web page has been changed, and that the encapsulated content has been removed in the latest version, but this author is incorrectly using it to add a strikethrough effect to his text. (The author has also forgotten to add an <acronym> tag, but this isn't as important.) This is simple to clean up:


<p class="large">Did you know I'm so good at <acronym title="HyperText Markup Language">HTML</acronym>, I can make <span class="strikethrough">text strikethrough</span>? Isn't that cool?!</p>

The final section in our bad example page is also the largest, but only contains a few mistakes repeated many times:


<table border="1" width="100%">
<tr>
<td>
<cite>Here's a recent conversation I had with a friend of mine:</cite>
</td>
<td>
<dl>
<dt>Mark said:</dt>
<dd>So, have you looked into this new <q>semantic markup</q> thing?</dd>
<dt>DrBob said:</dt>
<dd>Hell no! I'm the best coder in the world already!</dd>
<dt>Mark said:</dt>
<dd>Are you sure? It looks like it has benefits.</dd>
<dt>DrBob said:</dt>
<dd>Go away. I hate you.</dd>
</dl>
</td>
</tr>
</table>
</body>
</html>

As you can see, the section contains a conversation log of an interaction between the author and one of his (no longer) friends. The first mistake is a blindingly obviously incorrect usage of a table. Many people have said it many times, and it can't hurt to say it again: tables should be used to display tabular data only, not used to lay out a page! The next mistake is the use of a citation tag in the wrong place. Citation tags should be used to show who a quote came from, and not at all in the manner shown in the example. The remaining mistakes in this section are all misuses of definition elements. The HTML specification defined several elements for use in defining terms. Here, they have been used to format the responses in a chat log, and this is completely wrong — if a computer were to read this page, it would record that "Mark said:" means "So, have you looked into this new semantic markup thing?", among other things.

A final mistake in this section is the incorrect use of a quote tag. As nobody said "semantic markup" (as far as any reader of the page can tell, anyway), it shouldn't be inside a <q> tag. Instead, it should just be quoted normally, as in the cleaned version:


<div class="float_left">
<p>Here's a recent conversation I had with a friend of mine:</p>
</div>
<div class="float_right">
<ul>
<li><cite>Mark</cite> said:
<blockquote><p>So, have you looked into this new "semantic markup" thing?</p></blockquote></li>
<li><cite>DrBob</cite> said:
<blockquote><p>Hell no! I'm the best coder in the world already!</p></blockquote></li>
<li><cite>Mark</cite> said:
<blockquote><p>Are you sure? It looks like it has benefits.</p></blockquote></li>
<li><cite>DrBob</cite> said:
<blockquote><p>Go away. I hate you.</p></blockquote></li>
</ul>
</div>
</body>
</html>

That concludes our little waltz through a semantically incorrect page. It has by no means covered every conceivable mistake regarding semantic readability, but it has covered the main ones. The main thing to think about when coding a web page, is what the actual meaning of the elements you are using is. Most of the time this is very obvious and self-explanatory, but if you're unsure at any time, it's always best to check with the W3C's specifications.

The future is sure to include more computers trawling through the internet looking for information. Whether it be the omnipresent Googlebot, or some university student's semantic web project, all computers need help in understanding web pages. Why make it harder for them, when it's so simple to make it easy?

For more information on common semantic mistakes, and the proper uses of elements involved in such mistakes, why not look at my semantics example page? It shows a table of common mistakes, and showcases some tricky (yet correct) semantics.

AJAX

OK. I've been wanting to write an article about the myriad wonders of Ajax almost since I first found out about it. Ajax is a very powerful and flexible technology (almost as good as XML :P), and I love raving about it. I've just found some time to write this article; I'm currently rather depressed with some work I've been doing for the past 8 hours, so I thought now was as best a time as any to sit down and spout. :)

Ajax is one of the most flexible technologies to come to fruition since the birth of the web. It's actually been around for quite a while, but lack of widespread browser support, and developer ignorance have kept it at bay. It's basically just a simple application of Javascript to download new data and utilise it, without actually reloading the whole page. This allows developers to keep server load down; load data unbelievably quickly make some snazzy interfaces; and generally impress the users: Ajax is a flashy technology.

So, on to the actual code.

The implementation of Ajax is rather simple - all the data is transferred using XML packets:

  • The transaction is initiated from the client-side, using Javascript
  • The Javascript uses an XMLHttpRequest object (or equivalent) to fetch a page from the server (typically from a dynamic script)
  • It sets an "onreadystatechange" function to catch the response, and then exits
  • The "onreadystatechange" function catches the response from the server, and parses the XML
  • It then dynamically calls the respective function to deal with the actual data received

var req;

function load_XML_doc(url)
{
if(window.XMLHttpRequest)
{
//Branch for decent browsers' XMLHttpRequest object
req=new XMLHttpRequest();
req.onreadystatechange=process_req_change;
req.open("GET",url,true);
req.send(null);
}
else if(window.ActiveXObject)
{
//Branch for IE :(
req=new ActiveXObject("Microsoft.XMLHTTP");
if(req)
{
req.onreadystatechange=process_req_change;
req.open("GET",url,true);
req.send();
}
}
}

This function is called on the client-side when you want to initiate an Ajax transaction. It requests a document from the server, sets a function to catch the response, then disappears. It uses different methods of communication for different browsers (Gecko / MSIE), but the end result is still the same.

function process_req_change()
{
//If req is 'complete'
if(req.readyState==4)
{
//If status is 'OK'
if(req.status==200)
{
//Process the result
response=req.responseXML.documentElement;

var method=response.getElementsByTagName("method")[0].firstChild.data;
var result=response.getElementsByTagName("result")[0].firstChild.data;
var resultpos=response.getElementsByTagName("resultpos")[0].firstChild.data;
resultpos--;

var eval_text=method+"(";
for(var i=0;i<resultpos;i++)
{
eval_text=eval_text+"'',";
}
eval_text=eval_text+"result);";

eval(eval_text);
}
else
{
alert("There was a problem retrieving the XML data:n"+req.statusText);
}
}
}

This function receives the XML data packet sent by the server, extracts the useful data, and calls the right function to handle said data. Note that the XML handling is all done through the DOM. No IE-only old methods for Ajax. ;)

This is all fine and well...but without the XML data format, everyone's a bit stuck:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<method>get_databases</method>
<result></result>
<resultpos>5</resultpos>
</response>

There are three main points of interest here:

  • The "method" tag: it contains the name of the Javascript function that will handle the returned data
  • The "result" tag: it contains the actual data to be used
  • The "resultpos" tag is my own addition: if you want to have the contents of the "result" tag passed to the "method" Javascript function in some parameter position other than 1, set it here. ;)

This data has to be sent with a certain MIME type ("text/xml"). The following PHP code will achieve that:

header('Content-Type: text/xml;charset=iso-8859-1');
header('Vary: Accept');

So, we have two abstract functions for dealing with XML-RPC, a format for the XML data packets, and a snippet of PHP for header manipulation. Time to write a sample Javascript function to actually call something!

function get_message(message_number,response)
{
if(response!='')
{
//Deal with the response
window.alert("Received message: "+response);
}
else
{
//Make the query!
var url="sample.php?message_number="+message_number;
load_XML_doc(url);
}
}

This function is exceedingly simple, but it manages to deal with the sending and handling of the data.

Coupled with a PHP script ("sample.php"):

<?php
header('Content-Type: text/xml;charset=iso-8859-1');
header('Vary: Accept');

echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<method>get_message</method>
<result>';

switch($_GET['message_number'])
{
case 1:
echo 'Hello world!';
case 2:
echo 'Goodbye world.';
default:
echo 'Unknown message_number.';
}

echo '</result>
<resultpos>2</resultpos>
</response>';
?>

That should work, and give you a nice little spiced up "Hello world" script - using Ajax

To make things a little friendlier for the user, you could use DOM manipulation to place results in the page dynamically.

For some neat (even if I do say so myself!) examples of Ajax in action, see Helios :D

XML

XML is the latest buzzword in web development. It is supposed to solve everyone's problems, be really simple and easy to use, and have a lot of power.

Well…it won't solve all your problems, but it does harbour a lot of flexibility.

The whole point of XML is that it is what you want it to be. It is a markup language, that can be customised by you. "How then", I hear you ask, "can it be shown by browsers, if it uses tags that they've never seen before?". Well, frankly, it isn't. XML on its own can't really be presented in a meaningful way by a browser. For that, you need XSLT to transform it into XHTML; I will cover this in a later article.

Enough of the talk, let's get down to some code!

All you need to declare an XML document, is the following line, and a MIME type of "text/xml"

<?xml version="1.0" encoding="ISO-8859-1"?>

Once you've done that, you can then proceed to use whatever tags you like, in whatever structure you like, providing you follow the basic rules of XML (outlined in the XHTML tutorial). (All tags and attributes are lower-case, tags should always be closed, or self-closing, all attribute values should be enclosed in double-quotation-marks, and should all have a value.)

e.g.

<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
<channel>
<title>rakaz</title>
<link>http://www.rakaz.nl/nucleus/</link>
<description></description>
<language>en-us</language>
<generator>Nucleus v3.15</generator>
<copyright>Copyright 2005, Niels Leenheer</copyright>
<category>Weblog</category>
<item>
<title>Nucleus skins</title>
<link>http://www.rakaz.nl/nucleus/index.php?itemid=49</link>
<description>...</description>
<category>nucleus</category>
<comments>http://www.rakaz.nl/nucleus/index.php?itemid=49</comments>
<pubDate>Thu, 3 Feb 2005 22:01:05 +0100</pubDate>
</item>
</channel>
</rss>

That is XML used to create an RSS feed for Rakaz's blog

There are, however, more things you can do with XML. Namespaces allow you to effortlessly mix several different markup languages in one document. Using a namespace, you can put XHTML markup in an XML document, and vice-versa. To use a namespace, you must first declare it.

xmlns:namespacename="http://www.w3.org/TR/html4/"

That code usually goes into the first tag in the document. 'namespacename' is the name of the namespace, and the URI following it should be unique. It isn't actually used to do anything but identify the namespace. You may have multiple namespaces declared, just as long as they don't have the same name or URI.

To use the namespace, you prefix the namespace name onto any tag you want in that namespace, with a colon.

<namespacename:tagname>...</namespacename:tagname>

You may also use the default namespace format.

xmlns="http://www.w3.org/TR/html4/"

That code would be put into a tag, and that tag, and all its children would then belong in the specified namespace. This saves us from having to type the namespace name in front of all the tags.

So, how can we use this to embed XHTML in XML? Well, we would have to declare the XHTML namespace: xmlns:xhtml="http://www.w3.org/TR/xhtml11/"

We would then have to prefix all XHTML elements with the 'xhtml' prefix.

e.g.

<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0" xmlns:xhtml="http://www.w3.org/TR/xhtml11/">
<channel>
<title>rakaz</title>
<link>http://www.rakaz.nl/nucleus/</link>
<description></description>
<language>en-us</language>
<generator>Nucleus v3.15</generator>
<copyright>Copyright 2005, Niels Leenheer</copyright>
<category>Weblog</category>
<item>
<title>Nucleus skins</title>
<link>http://www.rakaz.nl/nucleus/index.php?itemid=49</link>
<description><xhtml:p>This is some <xhtml:strong>sample</xhtml:strong> text.</xhtml:p></description>
<category xmlns="http://www.w3.org/TR/xhtml11/"><strong>default namespace usage</strong></category>
<comments>http://www.rakaz.nl/nucleus/index.php?itemid=49</comments>
<pubDate>Thu, 3 Feb 2005 22:01:05 +0100</pubDate>
</item>
</channel>
</rss>

Another advanced feature of XML is the CDATA syntax. This nifty little mabob allows you to put markup into an XML document, but have it appear as plain text. This is useful for preventing people from using XHTML in blog comment syndications, for example. To use CDATA, just surround the required markup with <![CDATA[, and ]]>.

e.g.

<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
<channel>
<title>rakaz</title>
<link>http://www.rakaz.nl/nucleus/</link>
<description></description>
<language>en-us</language>
<generator>Nucleus v3.15</generator>
<copyright>Copyright 2005, Niels Leenheer</copyright>
<category>Weblog</category>
<item>
<title>Nucleus skins</title>
<link>http://www.rakaz.nl/nucleus/index.php?itemid=49</link>
<description><![CDATA[<description>The XML tags in <item>this</item> section won't be parsed, preventing unwanted markup from accidentally messing up newsreaders, etc.</description>]]></description>
<category>nucleus</category>
<comments>http://www.rakaz.nl/nucleus/index.php?itemid=49</comments>
<pubDate>Thu, 3 Feb 2005 22:01:05 +0100</pubDate>
</item>
</channel>
</rss>

Hopefully this little XML tutorial has been of some use. Next time, I will try and give a fairly useful article on XSLT, even though it is a hugely complex language, and I haven't learnt it all yet :P

Standards-compliant web design

I find it annoying that so many web developers, and web development programs (read: Microsoft Frontpage) don't support established web standards properly. What I find even more annoying are web developers who arrogantly refuse to use such web standards because the markup they use (usually Microsoft HTML) is 'far superior' to, 'easier and faster to code' than, and 'a lot more widespread' than standards such as XHTML.

I can sort of see where they are coming from: as so many people use older browsers such as Microsoft Internet Explorer 6, what's the point in coding things that will work with anything else? I mean, who would use such low-key pieces of software as Mozilla Firefox, Opera, Mozilla Suite, Konqueror, Safari, Lynx, or WebTV?

However, this argument is fundamentally flawed: what is the problem with using new standards such as XHTML 1.0 Strict, that work with older and newer browsers? What is the problem with using CSS/DIV-based design, when it works reasonably well in Internet Explorer? What is the problem with using PNG instead of GIF? All these paradigms work together well, and produce outstanding websites, such as SpreadFirefox.com

I admit, I myself don't quite do all of this: I do use JPG instead of PNG images, but that is only because of bandwidth constraints on my webspace. PNG has never been as good as JPG for lossless compression.

Then again, there is another side to the argument, where people argue that websites should always use the very latest in cutting-edge technology: XHTML 1.1 Strict, CSS 2 and SVG 1.1. These people are the drivers of the progression of the web development caravan. They push ahead new standards to widespread acceptance, and make sure that people know about them, and that browser developers are always on their feet. However, these people are likely to be constantly rebuilding their websites from the ground up, to cater for a new technology, or revision of old markup. They are also likely to have websites that don't display to their full and intended potential in most browsers, as browser developers can never keep up with the standards developers. I am likely to lean towards this stance more than the others, as I like to embrace new technology. However, I do not take this view without a generous pinch of salt, as I don't want to be a slave to the ever-renewing standards.

What thinks you all?