Clean Up Your Page, Removing Bad Behaviour

Cliché, cliché, cliché… What old analogy can I use to sum up this little tutorial? I think I’ve decided on one.

Would you wear walking, speak T-shirts or skull around all day? I think not. Actually, I will make a fairly confident statement and say that your eyebrows made a slight movement towards the ceiling while reading those questions, or at the very least you attempted to put on a pair of walking or got up and tried to skull around.

As cryptic as the analogy is, it makes perfect sense for this tutorial. You do not want to mix behaviour with your presentation. You want to wear something designed for the task like a T-Shirt. You do not want your behaviour jumping in amongst your structure either; we do not have a pirouette bone in our body because this behaviour is not part of our structure. Our structure, presentation and behaviour all work together but are separate parts of us as a whole.

Would you wear walking, speak T-shirts or skull around all day? I think not. Actually, I will make a fairly confident statement and say that your eyebrows made a slight movement towards the ceiling while reading those questions, or at the very least you attempted to put on a pair of walking or got up and tried to skull around.

As cryptic as the analogy is, it makes perfect sense for this tutorial. You do not want to mix behaviour with your presentation. You want to wear something designed for the task like a T-Shirt. You do not want your behaviour jumping in amongst your structure either; we do not have a pirouette bone in our body because this behaviour is not part of our structure. Our structure, presentation and behaviour all work together but are separate parts of us as a whole.

I know, I know… I have not told you what it is this tutorial is about yet and judging by your general restlessness and tooth grinding, you are dying to find out. Well, I have always been terrible at keeping secrets so I will spill the beans.

Separating Behaviour (JavaScript) From Structure and Presentation

As frustrating as it can sometimes be to code your websites to comply with some of the recommendations and specifications set down by the World Wide Web Consortium (W3), these standards do have your best interests at heart. Sure, it may take a little longer to learn the correct way and in some cases it may take a little longer to write the mark-up but their recommendations really do make things easier, not only for you, but also for your users.

If you are like me and learned HTML before anything else in the WWW, you would probably have spent a large amount of time learning to use the archaic HTML presentational elements to create your pages. Something as simple as a colourful paragraph would require ludicrous overuse of tags and color=”" attributes. HTML was suffering badly, my website source-code was a sickening tag soup and the humble HTML, a procedural, structural, mark-up language was being asked to do much more than it was designed to do.

My battle – and the long-suffering HTML’s battle– with these elements ended when I discovering the heroic Cascading Style Sheet. What was so special about CSS that it was able to make my life as a web designer that much easier? It took the presentation of web documents and separated it from the structure. No longer was it necessary to fiddle about inside ridiculous numbers of presentational tags to get the look and feel required by my creative mind. I was able to shift the presentation to a document and format designed exactly for the cause and in doing so I was able to relieve the burden placed on the structure of my pages.

It did not take long for the benefits of CSS to become clear — portable, abstracted presentation allowing for site-wide layout modifications by changing a single file.

It was not perfect though; there are three aspects to a website — structure, presentation and behaviour. CSS had taken the presentation out of the equation but my HTML was left littered with behavioural modifiers. My growing skills with Dynamic HTML gave me motivation to enhance my pages but the gap left by presentational code I had moved to CSS was quickly filling with behavioural JavaScript code. This last bit of separation anxiety was extinguished when I became aware of yet another W3 recommendation, The Document Object Model, giving me a way to isolate behaviour leaving HTML to do what it is best at, structuring content.

The Document Object Model

So what is the Document Object Model (DOM) and what tricks does it bring to the party that earns it such following of eager young lasses web designers?

The DOM is an Application Programming Interface designed to access and manipulate objects contained within documents of a hierarchal nature… What is that you say? You just want to mess about with a web page not start flipping around in hierarchy nonsense?

Well that is the thing. The DOM gives client side developers a way to reach any element in a (x)HTML page from an abstracted layer outside of the structure. In the same way as CSS removed website presentation from the HTML structure, the DOM removes website behaviour from the structure. From a specialised document, you can control the behaviour of a webpage and finally leave HTML to control the structure – the job HTML was created to perform.

Strictly coded HTML and xHTML implements a logical structure and has a hierarchy whereby every element has a parent element all the way up to the root element – the element is the root of every HTML page. So using this HTML family tree, you can traverse your way to any element simply by looking down through the generations of children. The first

element of your web page would be the great-grandchild of the element.

 -->  -->

Okay, so you can see now that it is possible to drill your way down to any element you desire, let’s start having a look at what problems the DOM solves and some of the methods available for us to achieve them.

JavaScript, unbelievably, is a very powerful Object Oriented language that allows many of the OOP philosophies to be brought across to client side coding. The major philosophy here is abstraction – moving the behavioural logic into a layer above the structure and presentation.

The examples below will all be manipulating one simple HTML document from an external .js file. The HTML document follows – you may use any HTML page for these examples as the code can simply be attached to another page, nothing is hard-coded into the HTML structure.

Please take the time to read the points described in the HTML file to understand the benefits of coding with the DOM.

As discussed above, the root or top-level parent of a HTML document is the tag. The JavaScript keyword document can be considered “The ” tag for purposes of understanding the correct hierarchy. Just about all of the DOM traversing methods available for document can be used on more specific child elements as well.

www.lukedingle.com/scripts/dom.php is where you can see and download the HTML. Note that this page is just a normal functioning HTML page. There will be no changes made to the HTML at all.

Traversing the DOM

Accessing a Single Element

Something that you will want to do again and in your JavaScript’s is isolate a single element on your page and perform some sort of action with it. It could be any element, and you can perform any JavaScript actions on it. The easiest and most direct method to do this is with getElementById.

The getElementById method takes a single string as its argument. This string is the id=”" attribute of a HTML element. If the given string matches an id attribute within the document, the function will return a reference to that element. If it does not match, this function will return null.

Let’s have a look at an example usage. The following code will get a reference to the #header div in our document. It will then change the background colour when the user moves their mouse over the div.

// This function will be added to throughout the tutorial
// This function will be run when the a page loads and will set up
// The various things using the DOM

var backgroundColour = '#EEEEEE'; // This is the colour the background will turn on mouseover
var date = new Date();		 // a date object to use later
var infoDiv = 'border';			 // This is the div we will be adding text to later
var externalFlag = 'external';   // The class name given to links to external sites

var message      = 'Oh! Please don't leave so soon! By clicking okay, you will go to another site. Are you sure you want to?'; // Message on leaving

function initiatePage ()
{
	// Let's get a reference to the #header div in our document.
	var header = document.getElementById('header');

	// Now, we'll attach the background colour changing function
	// to the header div's onmouseover and onmouseout event handlers

	header.onmouseover = changeBackground;
	header.onmouseout  = changeBackground;
}

function changeBackground()
{
	if (this.style.backgroundColor == '')
	{
		this.style.backgroundColor = backgroundColour;
	} else {
		this.style.backgroundColor = '';
	}
}

// Attach the initiatePage function to the onload event handler of the window object
window.onload = initiatePage;

See results at : www.lukedingle.com/scripts/dom.php?getCode

Pretty simple hey? Without a single line of code in the HTML page we are able to eliminate an onmouseover=”" onmouseout=”" and perhaps even a tag to declare the function.

A few things to note from the preceding code that may seem a little different to what you’re used to.

  • Once you have a reference to a HTML node stored in a variable, you can treat it like any other JavaScript object. This includes adding custom properties and methods. You just get the benefit of having all the default properties and methods for the type of element.
  • You can assign a function to a method in two ways. You can define a function and add it using the function name (note that you don’t use parentheses as this will execute the function) or you can add it as an inline function declaration.
    var.method = function () { /* function code here */};
  • When you are creating functions to be assigned to objects, you can use the this special variable. The this variable can basically be replaced with “The object that this function is attached to”. It gives you a way of attaching the same function to as many objects as you desire without having to worry about variable names.

Pages: 1 2 3

5 Comments on "Clean Up Your Page, Removing Bad Behaviour"

  1. Luke Dingle says:

    Hey Alex,

    Glad you like what we’re doing here. Hopefully we’ll keep feeding you the good stuff through RSS.

Got something to say? Go for it!