Wednesday, October 31, 2007

Building Dynamic Web Sites


Use our brief overview to find out about the building blocks that make up DHTML websites – from what HTML really is, to adding interactivity using JavaScript…


DHTML is actually a combination of proper HTML for your content, Cascading Style Sheets for your design and JavaScript for interactivity. Mixing these technologies together can result in a humble stew or a grandiose buffet. It’s all in the art of cooking, so let’s begin…


HTML starting points


Websites are written in HTML. For a successful DHTML-enhanced website, it’s critical that your HTML is two things: valid and semantic. These needs may necessitate a shift away from your previous experiences writing HTML. They may also require a different approach.


A specific set of rules, set out in the HTML recommendation, dictate how HTML should be written. HTML that complies with these rules is said to be “valid”. Your HTML needs to be valid so that it can be used as a foundation on which you can build DHTML enhancements. While the set of rules is pretty complex, you can ensure that your HTML is valid by following a few simple guidelines.


Correctly nest tags


Don’t let tags “cross over” one another. For example, don’t have HTML that looks like this:


Here is some <strong>bold and <em>italic</strong> text</em>.


Here, the <strong> and <em> tags cross over one another; they’re incorrectly nested. Nesting is extremely important for the proper use of DHTML. If you cross your tags, each browser will interpret your code in a different way, according to different rules (rather than according to the standard). Any hope of your being able to control the appearance and functionality of your pages across browsers goes right out the window unless you do this right.


Close container tags


Tags such as <strong> or <p>, which contain other items, should always be closed with </strong> or </ p>, or the appropriate closing tag. It’s important to know which tags contain things (e.g. text or other tags) and to make sure you close them. <p>, for example, doesn’t mean “put a paragraph break here”, but “a paragraph begins here”, and should be paired with </p>, “this paragraph ends here”. Those who know what they’re doing with container tags will be aware that HTML 4.01 doesn’t actually require that all container tags are closed, though XHTML still does. However, it’s never invalid to close a container tag, though it is sometimes invalid to not do so. It’s considerably easier to just close everything than it is to remember which tags you’re allowed to leave open. The same logic applies to <li> tags as well.


Always Use a Document Type


A document type (or DOCTYPE) describes the dialect of HTML that’s been used; there are several different options. Here, we’ll use the dialect called HTML 4.01 Strict. Your DOCTYPE should look like this:


<!DOCTYPE HTML PUBLIC “-//W3C [13]//DTD HTML 4.01//EN”

“http://www.w3.org/TR/html4/strict.dtd”>


That information can be typed on a single line, or with a line break after EN”. Be sure to place it at the top of every page. The article Fix your site with the right DOCTYPE! published on www.alistapart.com lists all the DOCTYPEs you might want to use.


The most important page creation step is to check that your HTML is valid. There are numerous tools that you can download and run to test your code’s validity – some HTML editors even have such tools built in – or you can use one of the many online validators, the most common of which is the W3C’s own validator (validator.w3.org). A validator will tell you how you need to adjust your HTML in order to make it compatible with DHTML techniques. The ultimate reference for what constitutes valid HTML is the HTML recommendation (www.w3.org/TR/html4). It’s complex and detailed, but you’ll find the answers there. As mentioned above, browsers rely on a standard that describes how validated HTML should be interpreted. However, there are no standards to describe how invalid HTML should be interpreted; each browser maker has established their own rules to fill that gap. Sticking to valid HTML means that any problems you find are deemed to be bugs in that browser – bugs that you may be able to work around.


Step up to semantic HTML


In addition to its validity, your HTML should be semantic, not presentational. What this means is that you should use HTML tags to describe the nature of an element in your document, rather than the appearance of that element. So don’t use a <p> tag if you mean, “put a blank line here”. Use it to mean, “a paragraph begins here” (and place a </p> at the end of that paragraph). Don’t use <blockquote> to mean, “indent this next bit of text”. Use it to mean, “this block is a quotation”. If you mark up your HTML in this way, you’ll find it much easier to apply DHTML techniques to it further down the line. This approach is called semantic markup – a fancy way of saying, “uses tags to describe meaning”.


Let’s look at a few example snippets. First, imagine your website has a list of links to different sections. That list should be marked up on the basis of what it is: a list. Don’t make it a set of <a> tags separated by <br> tags; it’s a list, so it should be marked up as such, using <ul> and <li> tags. It might look something like this:


<ul>

<li><a href=”index.html”>Home</a></li>

<li><a href=”about.html”>About this Website</a></li>

<li><a href=”email.html”>Contact details</a></li>

</ul>


You’ll find yourself using the <ul> tag a lot. Many of the items within a website are lists: a breadcrumb trail is a list of links, a menu structure is a list of links and a photo gallery is a list of images. If your list contains items with which comments are associated, it should be marked up as a definition list:


<dl>

<dt><a href=”index.html”>Home</a></dt>

<dd>Back to the home page</dd>

<dt><a href=”about.html”>About this Website</a></dt>

<dd>Why this site exists, how it was set up, and who did it

</dd>

<dt><a href=”email.html”>Contact details</a></dt>

<dd>Getting in contact with the Webmaster: email addresses and phone numbers</dd>

</dl>


Remember: the way your page looks isn’t really relevant. The important part is that the information in the page is marked up in a way that describes what it is. There are lots of tags in HTML; don’t think of them as a way to lay out information on your page, but as a means to define what that information means. If you don’t use HTML to control the presentation of your pages, how can you make them look the way you want them to? That’s where Cascading Style Sheets come in.


Adding CSS


Cascading Style Sheets (CSS) is a technique that enables you to describe the presentation of your HTML. In essence, it allows you to state how you want each element on your page to look. An element is a piece of HTML that represents one thing: one paragraph, one heading, one image, one list. Elements usually correspond to a particular tag and its content. When CSS styles are used, DHTML pages can work on the appearance and the content of the page independently. Imagine you want your main page heading (an <h1> tag) to be displayed in big, red, centred text. You should specify that in your style sheet as follows:


h1 {

font-size: 300%;

color: #FF0000;

text-align: center;

}


See More information for some links to introductory tutorials on CSS, which should help if the above lines don’t make a lot of sense to you.


The key point here is to remove the presentation aspects from your HTML and put them into your style sheet. If, for example, you made your page heading bigger by putting <font> tags in your HTML, then you’d need to paste those tags into every page on which a header was used. By making your HTML semantic and moving the page’s presentation into CSS, you can control the look of headings across the whole site through a single style sheet.


Of course, it’s not quite as easy as that. Although the full definition of CSS enables you to do some fairly amazing things, and to control the presentation of your pages to a high degree, not every browser supports everything that CSS has to offer.


In order to know about the differences in browser support for CSS, you need to know what CSS can do. There are two sorts of browser incompatibilities: things that a given browser doesn’t implement and things that it implements incorrectly.


Missing implementations are relatively easy to deal with: don’t rely on such rules if you want your CSS to work in browsers that have failed to implement them. This can be a pain, especially since the most commonly used browser in the world, Internet Explorer for Windows, has some serious holes in its CSS support; however, this “solution” is often a necessary compromise.


Badly implemented standards are a bigger problem. In such cases, the browser gets it wrong. You’ll need to understand exactly what each browser does wrong, and how you can work around those failings. You’ll pick up this knowledge as you go along. Workarounds for CSS bugs in different browsers are usually achieved using CSS hacks. These hacks take advantage of the bugs in a browser’s CSS parser to deliver specific style sheet directives that work around its poor implementation of the standards. A huge variety of these CSS hacks is documented for each browser in various places around the web.


Learning to understand and adapt to the vagaries of CSS handling in various browsers is part of the work that’s required to use CSS effectively. While it can be a lot of work, many CSS bugs only become apparent with the complex use of this technology; most CSS is handled perfectly across platforms and browsers without the need for hacks or complex tests. While CSS is powerful, it doesn’t quite give us true flexibility in presentation. The capabilities of CSS increase all the time, and more “interactive” features are constantly being added to the CSS specification. However, it’s not designed for building truly interactive websites. For that, we need the final building block of DHTML: JavaScript.


Adding JavaScript


JavaScript is a simple but powerful programming language. It’s used to add dynamic behaviour to your website. HTML defines the page’s structure and CSS defines how it looks, but actions, the things that happen when you interact with the page are defined in JavaScript. JavaScript works with the Document Object Model to attach actions to different events (mouseovers, drags, and clicks). The ‘More information’ box below has some links to a few JavaScript tutorials if you need them.




MORE INFORMATION



www.sitepoint.com/article/css-is-easy

SitePoint’s easy introduction to the world of CSS is a great place to start.


www.w3schools.com/css

W3Schools’ CSS tutorials are helpful whether you’re learning from scratch, or simply brushing up on your knowledge of CSS.


www.csszengarden.com

The CSS Zen Garden is a marvellous demonstration of the power of cascading style sheets alone. It has a real wow factor!


www.centricle.com/ref/css/filters

This comprehensive list of CSS hacks shows you which browsers will be affected by a given hack, if you need to hide certain CSS directives (or deliver certain directives) to a particular browser.


www.positioniseverything.net

This site demonstrates CSS issues in various browsers and explains how to work around them.


www.css-discuss.org

The CSS-Discuss mailing list is ‘devoted to talking about CSS and ways to use it in the real world; in other words, practical uses and applications.’ The associated wiki is a repository of useful tips.


www.sitepoint.com/books

If you’re after something more definitive, HTML Utopia: Designing Without Tables Using CSS is a complete guide for the CSS beginner. The CSS Anthology: 101 Tips, Tricks & Hacks is a perfect choice if you prefer to learn by doing. A lot of tutorials on the web cover JavaScript. Some explore both DHTML and the DOM, while others do not; you should try to find the former.


www.sitepoint.com/article/javascript-101-1

This tutorial provides an introduction to the basics of JavaScript for the total non-programmer. Some of the techniques in this article aren’t as modern as the alternatives we’ve presented here, nonetheless you’ll get a good feel for the JavaScript language itself.


www.quirksmode.org

Freelance web developer Peter-Paul Koch’s list of CSS and JavaScript techniques and scripts covers a considerable amount of useful ground in this area.




A simple JavaScript example


Here’s a simple piece of JavaScript that converts a text field’s value to uppercase when the user tabs out of the field. First let’s see the old, bad way of doing it:


<input id=”street” type=”text” onchange=”this.value = this.value.toUpperCase();”>


Here we’ll recommend a more modern technique. First, the HTML:


<input id=”street” type=”text”>


Second, the JavaScript, which is usually located in the <head> part of the page:


<script type=”text/javascript”>

function uppercaseListener() {

this.value = this.value.toUpperCase();

}

function installListeners() {

var element = document.getElementById(‘street’);

element.addEventListener(‘change’, uppercaseListener,

false);

}

window.addEventListener(‘load’, installListeners, false);

</script>


The first function does the work of converting the text. The second function makes sure that the first is connected to the right HTML tag. The final line performs this connection once the page has loaded in full. Although this means more code, notice how it keeps the HTML content clean and simple.


Get some tools!


A good JavaScript development environment makes working with JavaScript far easier than it would otherwise be. Testing pages in Internet Explorer (IE) can leave something to be desired; if your page generates JavaScript errors, IE isn’t likely to be very helpful at diagnosing where, or what, they are. The most useful, yet simple, tool for JavaScript debugging is the JavaScript Console in Mozilla or Mozilla Firefox. This console will clearly display where any JavaScript error occurs on your page, and what that error is. Mozilla Firefox works on virtually all platforms, and it’s not a big download. It also offers better support for CSS than Internet Explorer, and should be part of your development toolkit. Beyond this, there’s also the JavaScript debugger in Mozilla, which is named Venkman. It can be useful, but be aware that it takes a bit of setting up. In practice, though, when you’re enhancing your site with DHTML, you don’t need anything as complex as a debugger; the JavaScript Console and judicious use of alert statements to identify what’s going on will help you through almost every situation.


Another tool that’s useful is a good code editor in which to write your website. Syntax highlighting for JavaScript is a really handy feature; it makes your code easier to read while you’re writing it, and quickly alerts you when you leave out a bracket or a quote. A good editor will seriously speed up your coding work. Plenty of powerful, customisable editors are available for free. But, if you’re currently writing code in Windows Notepad, have a look at what else is available to see if any other product offers an environment that’s more to your liking. You’ll want syntax highlighting, as already mentioned; a way to tie in the external validation of your pages is also useful. Textpad and Crimson Editor are Windowsbased editors that cover the basics if you’re developing on a Windows platform; Mac users tend to swear by BBEdit; Linux users have gedit or Kate or vim to do the basics, and there’s always Emacs. JavaScript is the engine on which DHTML runs. DHTML focuses on manipulating your HTML and CSS to make your page do what the user wants, and it’s JavaScript that effects that manipulation. This article outlines the very basic building blocks of DHTML. Read DHTML Utopia: Modern Web Design Using JavaScript & DOM by Stuart Langridge (www. sitepoint.com) and discover the basic techniques you can use to start making your websites dynamic, plus advanced scripting techniques for building menus, forms and even whole dynamic web applications.


About the author


Stuart Langridge has been playing with the web since 1994, and is quite possibly the only person in the world to have a BSc in Computer Science and Philosophy. He invented the term ‘unobtrusive DHTML,’ and has been a leader in the quest to popularise this new approach to scripting. When not working on the web, he’s a keen Linux user and part of the team at open-source radio show LUGRadio. He likes drinking decent beers, studying stone circles and other ancient phenomena, and trying to learn the piano. Stuart contributes to Stylish Scripting: SitePoint’s DHTML and CSS Blog.

0 comments:

Post a Comment

Followers

 

Pablo Emmanuel Otaola. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com